[C++]——Learning Templates

Foreword:

What is a template? What can templates do? Learning templates with a curious attitude will definitely yield great gains.

1. Template

1.1 What is a template

Templates are C++ tools that support parameterized polymorphism. Using templates allows users to declare a general pattern for a class or function, so that certain data members in the class or parameters and return values ​​of member functions can be of any type.

1.2 The concept of template

Template refers to programming that uses types as parameters in the C++ programming language and supports general programming. The C++ standard library provides many useful functions, most of which combine the concept of templates, such as STL and iostream.

A template is a tool for parameterizing types.
Usually has two forms: function template and class template:

  • Function template: for functions with different parameter types only;
  • Class template: for classes with different types only of member variables and member functions.

In templates, the compiler generally does not perform type conversion operations, because if there is a problem with the conversion, the compiler will take the blame.

1.3 What templates can do

The purpose of using templates is to enable programmers to write type-independent code.

1.4 Generic templates

Generic programming: writing generic code that is independent of type is a means of code reuse. Templates are the basis of generic programming.

2. Function template

Function template compilation (twice):
1: Before instantiation, check the code itself for syntax errors.
2: During instantiation, check whether the call to the template code is legal.

2.1 Function template concept and format

concept:

A function template represents a family of functions that are type-independent and are parameterized when used to produce a type-specific version of the function based on the actual parameter types.

Format:

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

The case is as follows:

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

Note: typename is a keyword used to define template parameters. You can also use class (remember: you cannot use struct instead of
class)

2.2 Principle of function templates

The function template is a blueprint, which is not a function itself. It is a template for the compiler to generate a specific type of function using a usage method.
So in fact, templates hand over repetitive things that we should do to the compiler.

Network map:
Insert image description here

In the compiler compilation phase, for the use of template functions, the compiler needs to deduce and generate functions of the corresponding type based on the passed in actual parameter types for calling. For example: When using a function template with a double type, the compiler determines T as a double type through deduction of the actual parameter type, and then generates a code that specifically handles the double type. The same is true for character types.

2.3 Function template instantiation

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.3.1 Implicit instantiation

Implicit instantiation: Also called deduced instantiation, function parameters are passed, the types of template parameters are derived, and the corresponding functions are generated. (Let the compiler deduce the actual type of the template parameter based on the actual parameters)

2.3.2 Explicit instantiation

Explicit instantiation: specify the actual type of the template parameter in <> after the function name

2.4 Matching principles 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 the non-template function
2. For non-template functions And function templates with the same name, if other conditions are the same, the non-template function will be called first when calling and an instance will not be generated from the template. A template will be chosen if it can produce a function with a better match. (To put it simply, if there is a ready-made one, use the ready-made one, if there is a more suitable one, use the more suitable one, if not, just use the template)
3. Template functions do not allow automatic type conversion, but Ordinary functions can perform automatic type conversion

2.5 Separation of function template declaration and definition

You can declare and define separation
The difference is that template parameter declarations and definitions must be given

//声明
template<typename T>
void Swap(T& left, T& right);
//定义
template<typename T>
void Swap(T& left, T& right)
{
    
    
    T temp = left;
    left = right;
    right = temp;
}

3. Class template

3.1 Definition format of class template

//可以声明多个模板参数
template<class T1, class T2, ..., class Tn>
class 类模板名
{
    
    
    // 类内成员定义
};

3.2 Class template instantiation

Class template instantiation is different from function template instantiation. Class templates are instantiated explicitly. Class template instantiation needs to be followed by <> after the class template name, and then the instantiated type can be placed in <> , the class template name is not the real class, but the instantiation result is the real class.

  • For ordinary classes, the class name is the type
  • Forclass template, the class name is not a type, class name<type> is the type of the entire class

3.3 Separation of class template declaration and definition

// 类模板
// 注意:Stack不是具体的类,是编译器根据被实例化的类型生成具体类的模具
template<class T>
class Stack
{
    
    
private:
	T* _a;
	size_t _top;
	size_t _capacity;

public:
	// ...
	Stack(size_t capacity = 10)
		:_a(new T[capacity])
		,_top(0)
		,_capacity(capacity)
	{
    
    }

	~Stack(); // 析构函数,在类中声明,类外定义
};

// 注意:类模板中函数放在类外进行定义时,需要加模板参数列表
template<class T>
Stack<T>::~Stack()
{
    
    
	if (_a)
	{
    
    
		delete[] _a;
		_a = nullptr;
	}
	_top = _capacity = 0;
}

int main()
{
    
    
	// 类模板的使用都是显式实例化
    // Stack是类名,Stack<int>才是类型
	Stack<int*> st1;
	Stack<int> st2;

	return 0;
}

Note: The template does not support writing declarations to .h header files, and writing definitions to .cpp source files. This method of separating declarations and definitions in different files will cause A link error occurred.

4. Summary

Note: If a template is not instantiated, the compiler will not check its internal syntax.

advantage:

  1. Templates reuse code, save resources, and enable faster iterative development. This is why the C++ Standard Template Library (STL) was born.
  2. Enhanced code flexibility

shortcoming:

  1. Templates can lead to code bloat and longer compilation times
  2. When a template compilation error occurs, the error message is very messy and it is difficult to locate the error.

Guess you like

Origin blog.csdn.net/plj521/article/details/134982513