template function

For a simple addition operation, we give its code:
int add(int m, int n)
{
	return m + n;
}
But now the situation is a little more complicated. We now have to calculate the addition of floating point types, and we have to rewrite another code:
float add(float m, float n)
{
	return m + n;
}

In this case, as long as a new type appears, we will add new functions , and the utilization of the code is not high . Looking at these two functions, it is obvious that the only difference between integer addition and floating point addition is the parameter type and return value type. At this time, we might as well boldly give a function that can calculate both integer addition and floating-point addition. At this time, we have the idea of ​​generic programming that adapts to all data types.

Below we give the template function of the above code:

template<class T>
T add(T m, T n)
{
	return m + n;
}
When calling, specify the type, such as:
add<int>(1,2);

It can be seen that when the template method is used, its writing has nothing to do with the type, which can significantly improve the code reuse rate.


The template above is called twice during the process:

First time: Before instantiating, check the template for errors.

Second time: After instantiation, see if all calls are valid.

In fact, templates are not functions or classes. The process by which the compiler uses a template to generate a function or class of a specified type is called template instantiation.

A non-template function can coexist with a template function of the same name, and the function template can also be instantiated as the non-template function.

If there are template functions and functions in the program, the function will be called first, and the template will not be used to generate the function.



Guess you like

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