[Template Elementary]

Table of contents

1. Generic programming

 2. Function templates

2.1 Function template concept

2.2 Function Template Format

2.3 Principle of function template

2.4 Instantiation of function templates

 2.4.1 Implicit instantiation

2.4.2 Explicit instantiation

2.5 Matching principle of template parameters

 3. Class Templates

3.1 Definition format of class template

3.2 Instantiation of class templates

4 Summary


1. Generic programming

How to implement a general exchange function?

void Swap(int& left, int& right)
{
 int temp = left;
 left = right;
 right = temp;
}
void Swap(double& left, double& right)
{
 double temp = left;
 left = right;
 right = temp;
}
void Swap(char& left, char& right)
{
 char temp = left;
 left = right;
 right = temp;
}
Although it is possible to use function overloading, there are several disadvantages:
1. The overloaded functions are only of different types, and the code reuse rate is relatively low. As long as a new type appears, the user needs to add the corresponding function.
2. The maintainability of the code is relatively low, and one error may cause errors in all overloads.
Can you tell the compiler a model and let the compiler use the model to generate code according to different types ?

If such a mold can also exist in C++ , by filling the mold with different materials ( types ) to obtain castings of different materials ( that is, to generate specific types of codes) , it will save a lot of hair. Coincidentally, the predecessors have already planted the tree, and we only need to enjoy the shade here.
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.

 2. Function template

2.1 Function template concept

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 ( argument list ) {}

 Note: typename is used to define template parameter keywords , and class can also be used ( remember: struct cannot be used instead of class)

Just like the Swap function we implemented, we can use function templates to implement:

template<typename T>
void Swap( T& left, T& right)
{
 T temp = left;
 left = right;
 right = temp;
}

 When we use it, the template will automatically deduce the type of the variable, but an error will be reported if it is written like the following:

 Because the types of a and d are different, it contradicts the template defined above, and the processing method can be as follows:

Swap(a, (int&)d);
Swap((double&)a, d);

This is a forced transfer method, of course, you can also use two different parameters to modify the template.

template<typename T1,typename T2>

2.3 The principle of function template

So how to solve the above problem? Everyone knows that when Watt improved the steam engine, mankind started the industrial revolution and liberated productivity. Machine production eliminated many manual products. What is the essence, the repetitive work is handed over to the machine to complete. Someone gave an argument: lazy people create the world.

A function template is a blueprint. It is not a function itself, but a mold for the compiler to generate a specific type of function by using it. So in fact, the template is to hand over the repetitive things that we should have done to the compiler.

 

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. For example: when using a function template with a double type, the compiler determines T to be a double type through the deduction of the actual parameter type, and then generates a code that specifically handles the double type , and the same is true for the character type.

 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 .

 2.4.1 Implicit instantiation

Let the compiler deduce the actual type of the template parameter based on the actual parameter.

template<class T>
T Add(const T& left, const T& right)
{
 return left + right;
}
int main()
{
 int a1 = 10, a2 = 20;
 double d1 = 10.0, d2 = 20.0;
 Add(a1, a2);
 Add(d1, d2);
}

Here is the parameter type automatically deduced by the compiler.

2.4.2 Explicit instantiation

The actual type of the template parameter is specified in <> after the function name .

int main()
{
 int a = 10;
 double b = 20.0;
 
 // 显式实例化
 Add<int>(a, b);
 return 0;
}

It's possible like this. 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.

2.5 Matching principle of template parameters

1. A non-template 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.

// 专门处理int的加法函数
int Add(int left, int right)
{
 return left + right;
}
// 通用加法函数
template<class T>
T Add(T left, T right)
{
 return left + right;
}
void Test()
{
 Add(1, 2); // 与非模板函数匹配,编译器不需要特化
 Add<int>(1, 2); // 调用编译器特化的Add版本
}

Like the above program, the first one will call the first Add, and the second one will call the general template.

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 when calling and will not generate an instance from the template. If the template can produce a function with a better match, then the template will be chosen.

 This has already been said above.

3. Template functions do not allow automatic type conversion, but ordinary functions can perform automatic type conversion.

 3. Class Templates

3.1 Definition format of class template

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

 Take the stack we implemented in C language as an example, what should we do if we want to store multiple types?

Some people may say, that's not easy, isn't there typedef? Is it enough to modify the data type directly with typedef?

But if we think about this method more, we will know that it will not work. When we want two kinds of data to exist in different stacks at the same time, there is no way to deal with it. So how to deal with it correctly?

In C language, it is inevitable to re-create a stack, but in C++ we can use templates to deal with this problem.

template<class T>
class Stack
{
private:
	T* _a;
	int _top;
	int _capacity;
public:
	Stack(int capacity=4)
	{
		_a = nullptr;
		_sz = 0;
		_capacity = capacity;
	}
	~Stack()
	{
		//...
	}
	Stack(const Stack& st)
	{
		//...
	}
	push()
	{
		//...
	}
	pop()
	{
		//...
	}
	T top()
	{
		//...
	}
};

int main()
{
	Stack<int>st1(8);
	Stack<char>st2(16);
	return 0;
}

Some of the member functions are not implemented here. I believe you can implement them yourself. In addition, you must pay attention not to separate the definition and declaration when using templates to implement classes, otherwise a link error will be reported.

3.2 Instantiation of class templates

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.

 Like we used above:

// Vector类名,Vector<int>才是类型
Vector<int> s1;
Vector<double> s2;

4 Summary

This blog introduces what generic programming is, and on this basis, it introduces the concept of templates, and introduces the concepts and usage methods of function templates and class templates. If this article is helpful to you, can you support the blogger with one click and 3 links?

Guess you like

Origin blog.csdn.net/m0_68872612/article/details/128461455