[C++] Primary content of templates (function templates, class templates)


foreword

Tell the compiler a model, let the compiler use the model to generate code according to different types Templates
are divided into function templates and class templates

Today we just introduce some basic operations of function templates and class templates

insert image description here

1. Function template

1.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.

1.2 Function template format

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

1.3 The principle of the template:

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.

insert image description here

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 as 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

1.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 based on the actual parameter
    insert image description here
  2. Explicit instantiation: Specify the actual type of the template parameter in <> after the function name
    insert image description here
    insert image description here
    insert image description here

Two, class template

2.1 Definition format of class template

template<class T1, class T2, ..., class Tn>
class 类模板名
{
    
    
 // 类内成员定义
};

insert image description here

2.2 Points to pay attention to when defining and declaring separation

insert image description here

Guess you like

Origin blog.csdn.net/m0_74774759/article/details/131383623