次のコードをC++テンプレートでテストしています。私は関数intとfloatと関数テンプレートを使って二乗関数を書いています。私はテンプレート関数 - テンプレートが通常の関数をオーバーライドしますか
template function
25
template function
30.25
template function
25
template function
30.25
を期待しても
#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
で誰かが違いを説明できますか?
3番目の出力で、コンパイラに2つの選択肢がある場合は、テンプレート関数よりも正常です.http://en.cppreference.com/w/cpp/language/overload_resolution –