C++ custom templates (function templates, class templates)

C++ provides two template mechanisms: function templates and class templates

First, the function template

1. The so-called function template is actually to create a general function, whose function type and formal parameter type are not specified, and are represented by a virtual type. This generic function is called a function template. All functions with the same function body can be replaced by this template, you don't need to define multiple functions, you only need to define them once in the template. When calling a function, the system will replace the virtual type in the template according to the type of the actual parameter, thus realizing the functions of different functions.

2. Function template definition form 
template <type formal parameter table>    
The form of type formal parameters is:
            typename T1 , typename T2 , …… , typename Tn 

或     class T1 ,  class T2 , …… , class Tn

3、

 myswap<float>(a, b); //Display type call

 myswap(a, b); //automatic data type deduction  

4. The difference between function templates and ordinary functions:

Function templates do not allow automatic type conversion, while ordinary functions can do automatic type conversion.

Second, the class template

1. Class templates are used to implement the type parameterization of the data required by the class 

     Class templates are particularly important in representing data structures such as arrays, tables, and graphs, whose representation and algorithms are not affected by the type of elements they contain.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324776963&siteId=291194637