我正在用C++模板測試下面的代碼。我寫了一個使用int和float並使用函數模板的方形函數。模板功能 - 模板是否覆蓋正常功能
#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;
}
輸出是
template function
25
template function
30.25
int function
25
template function
30.25
雖然我預計
template function
25
template function
30.25
template function
25
template function
30.25
有人能解釋的區別?
在第三個輸出中,如果編譯器有兩個選擇,則比模板函數更好的正常功能.http://en.cppreference.com/w/cpp/language/overload_resolution –