Error-prone points of template use: matters needing attention when passing in parameters of different data types

Error-prone use of Template

#include <iostream>  
using namespace std;  
  
template<typename T>  
T const& Max(T const& var1, T const& var2)  
{  
    return var1 > var2 ? var1 : var2;  
}  
  
int main()  
{  
    int a = 10;  
    float b = 19.2;  
    const int& var = Max<int>(a, b);  
    cout << &var << endl; // 0000001EA577FB14  
    cout << &b << endl; // 0000001EA577FA14  
}  

 

In the above program, it is not difficult to find that when the input parameter data type is different, the following operations will be performed:

Coercively convert the actual parameter float of the passed-in function to the data type int const explicitly specified by the template, and put the converted data type into a new storage space, and then pass in the reference (int const&) of this space Function.

We see that the variable address returned by the function is not the same as the variable address we passed in. Therefore, we must pay attention to when the parameters we pass in need to be coerced to the template data type we explicitly specify, never return Enter a reference to the variable.

Guess you like

Origin blog.csdn.net/weixin_45590473/article/details/112120343