C++ template advanced

Polymorphism in C++ is mainly reflected in templates and inheritance. 

Inheritance can be understood as a collection of different data structures that are related to each other. Templates are completely independent data structures that do not depend on each other

Using templates in functions can automatically deduce the type according to the parameters passed in by the function, thus omitting a lot of repetitive code

For example, a summation function

template<typename T>
T add(T a, T b)
{
     return a + b;
}

This is the easiest way to use templates. Suppose now you want to implement a function, pass in a structure, and print out all the variables of the structure. Since C++ does not have a reflection mechanism, there is no way to determine the type of the variable in the template function, and there is no way to know which members of the structure variable are.

Solution

template<typename T>
void visit(T a)
{
return;
}

template<>
void visit(A a)
{
// print member
return;
}

template<>
void visit(B a)
{
// print member
return;
}

First define a template function, and then implement a function for each specific structure variable.

Guess you like

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