Sat*_*ish 0 c++ templates c++11
我正在使用c ++模板测试以下代码.我使用int和float以及函数模板编写了一个square函数.
#include <iostream>
using namespace std;
int square (int a){
cout << "int function" << endl;
return a*a;
};
float square (float a){
cout << "float function" << endl;
return a*a;
};
template <typename T>
T square (T x){
cout << "template function" << endl;
return x*x;
}
int main(){
cout << square<int>(5) << endl;
cout << square<float>(5.5) << endl;
cout << square(5) << endl;
cout << square(5.5) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是
template function
25
template function
30.25
int function
25
template function
30.25
Run Code Online (Sandbox Code Playgroud)
虽然我期待
template function
25
template function
30.25
template function
25
template function
30.25
Run Code Online (Sandbox Code Playgroud)
有人可以解释这个区别吗?
它不会覆盖任何东西,它是一个更好的匹配.那是因为5.5是类型的常量double,而不是类型的常量float.
您没有任何双重超载,因此模板被实例化.那是因为模板不需要从double到float的转换序列,而不是你的重载.
如果你使用float常量,如下:
cout << square(5.5f) << endl;
Run Code Online (Sandbox Code Playgroud)
它会打印出来
float function
Run Code Online (Sandbox Code Playgroud)