In C ++ programming language, a special function is called a template function. But in fact, it is somewhat the same as a common function. Here we will explain some precautions for C ++ template function overloading, which are different from those of common function applications.
1: If the instantiated template function is called the same as a non-template function, the non-template function is called. However, you can also specify to call the template function, such:
- Inline int const & max (int const & a, int const & B)
- {
- // For easy differentiation, the returned result is + 100
- Return a <B? A + 10: B + 100;
- }
- Template <typename T>
- Inline T const & max (T const & a, T const & B)
- {
- Return a <B? B:;
- }
- // The form of the template function after instantiation is the same as that of a non-template function.
You can use the following method to call the Template Function
- Int I = max <> (42, 66 );
2: Since the parameters reloaded by the c ++ template function are of type, type conversion is not supported. But non-template functions support type conversion:
- Inline int const & max (int const & a, int const & B)
- {
- Return a <B? B:;
- }
- Template <typename T>
- Inline T const & max (T const & a, T const & B)
- {
- Return a <B? B:;
- }
- // Because the template function does not support type conversion, the non-template max function will be called here
- Max ('C', 42.2 );
In the above Code, if max ('C', 42.2) wants to call the max function of the template, it must meet the conditions that both parameters and return values are of the same type. The given two parameters have different types, and the template function does not support type conversion. Therefore, if it cannot find the matching template function, it will call the non-template max function. However, if we forcibly use max <> ('C', 42.2) to call the template function, a compilation error will occur.
The preceding section describes the function overloading of the C ++ template.