[C++] Detailed introduction to templates - function templates, class templates


ヾ(๑╹◡╹)ノ" People always have to pay for their past lazinessヾ(๑╹◡╹)ノ"
Here is the picture description is Xiao Liu Shu


1. Generic programming

generic programming: Writing generic code that has nothing to do with types is a means of code reuse. Templates are the foundation of generic programming. [Not for a certain type]
template template keyword
template<class T>
template<typename T>

  • Template parameter learning can be compared to function parameters.
  • Template parameters pass types; function parameters pass object values.
  • The definition and declaration of the template do not support being in two files separately [link errors will occur, and all link errors are because the symbol table cannot be found] because the template T of the compiler cannot be determined, and the symbol table cannot be generated.
  • Templates do not support declarations and definitions in .h and .cpp respectively, and generally need to be placed in one file. Some places will be named .hpp [the header file and the definition implementation content are merged together] but it does not have to be .hpp, .h is also possible.

Solution [Declaration and definition are separated, and a link error occurs]

  1. Display instantiation specification (troublesome, not recommended)
//声明
template
void Swap<int>(int& left, int& right);

template
class Vector<int>;

template
class Vector<double>;
//原因是因为声明没有类型,那么我们就把类型给写出来
  1. without separating the two files

2. Function template

2.1 Concept of function template

A function template represents a family of functions. The function template has nothing to do with the type. It is parameterized when used, and a specific type version of the function is generated according to the type of the actual parameter.

2.2 Function template format

template<typename T1, typename T2,...,typename Tn>
return value type function name (parameter list) {}

template<typename T>//也可以是class T
void Swap(T& left, T& right)
{
    
    
	T tmp = left;
	left = right;
	right = tmp;
}
//函数模版

Note : typename is used to define template parameter keywords, and class can also be used (remember: struct cannot be used instead of class) [Swap library has it, you don’t need to implement it yourself]
Declaration and Definition

//声明
template<typename T>
void Swap(T& left, T& right);

//定义
template<typename T>
void Swap(T& left, T& right)
{
    
    
	T tmp = left;
	left = right;
	right = tmp;
}
//函数模版

Pay attention to the format of definition writing

2.3 The principle of function template

In the compiler compilation stage, for the use of template functions, the compiler needs to deduce and generate corresponding types of functions for calling according to the type of actual parameters passed in . [Calling is not the same function]

The type of a function template is deduced by the compiler based on the actual parameters passed to the formal parameters. If it cannot be deduced automatically, we need to display the instantiation and specify the template parameters.
The type of a class template is explicitly instantiated, explicitly specified.

2.4 Instantiation of function templates

When a function template is used with parameters of different types, it is called instantiation of the function template.
Template parameter instantiation is divided into: implicit instantiation and explicit instantiation
1. Implicit instantiation: let the compiler deduce the actual type of the template parameter according to the actual parameter passed to the formal parameter

template<typename T>//也可以是class T
void Swap(T& left, T& right)
{
    
    
	T tmp = left;
	left = right;
	right = tmp;
}
//函数模版

int main()
{
    
    
	int a = 1;
	int b = 2;
	Swap(a, b);//编译器根据实参传递给形参,判断为int
	double c = 1.2;
	double d = 2.3;
	Swap(c, d);//编译器根据实参传递给形参,判断为double
	return 0;
}

When the parameter types are different:

template<typename T>
T Add(const T& left, const T& right)//常量,需要有const
{
    
    
	return left + right;
}
int main()
{
    
    
	int a = 1;
	double c = 2.1;
	Add<int>(a, c);//c这里有一个隐式类型转换
	Add<double>(a, c);

	Add(a,(int)c);//c这里有一个隐式类型转换
	Add((double)a, c);
	return 0;
}

2. Explicit instantiation: Specify the actual type of the template parameter in <> after the function name

template<typename T>
T* func(int n)
{
    
    
	terurn new T[n];//new n个对象,,,,无法推导出T的类型
}
int main()
{
    
    
	int* p1 = func<int>(10);//函数模版显示实例化
	return 0;
}

If the types do not match, the compiler will try to perform an implicit type conversion, and if the conversion fails, the compiler will report an error.

The type of a function template is deduced by the compiler based on the actual parameters passed to the formal parameters. If it cannot be deduced automatically, we need to display the instantiation and specify the template parameters.

2.5 Matching principles of function templates

  1. A non-template function [specialized function] can exist at the same time as a function template with the same name, and the function template can also be instantiated as this non-template function.
  2. For a non-template function and a function template with the same name, if other conditions are the same, the non-template function will be called first and an instance will not be generated from the template when mobilizing . If the template can produce a function with a better match, then the template will be chosen.
  3. Template functions do not allow automatic type conversion, but ordinary functions can do automatic type conversion

Three, class template

3.1 Class template definition

template<class T1, class T2, ..., class Tn>
class class template name
{ // class member definition };

Class templates are not concrete classes, instantiations are real classes.

template<class T>
class Stack
{
    
    
public:
    // 使用析构函数演示:在类中声明,在类外定义。
	~Vector();
	//……
	void push(T x)
	{
    
    

	}

private:
	T* _a;
	int _top;
};
//类模板中函数放在类外进行定义时,需要加模板参数列表,每一个函数都需要加模板参数列表
template <class T>
Vector<T>::~Vector()
{
    
    
if(_pData)
     delete[] _pData;
_size = _capacity = 0;
}

int main()
{
    
    
	Stack<int> s1;
	s1.push(1);
	Stack<double> s2;
	s2.push(2.1);
	return 0;
}

When a function in a class template is defined outside the class, a template parameter list needs to be added

3.2 Class template instantiation

Class template instantiation is different from function template instantiation . Class template instantiation needs to follow the class template name with <>, and then put the instantiated type in <>. The class template name is not a real class , but the instantiated The result is the real class.

Vector class name, Vector<int>is the type Vector<int>s1; Vector<double>s2;


Summarize

The above is what I will talk about today. This article introduces function templates and class templates in detail. Hope to help friends!

Guess you like

Origin blog.csdn.net/m0_57388581/article/details/132513921