我有一個正常工作的重載函數。 (在這個例子中是f)。當我將它轉換爲同一事物的模板版本時,它總是調用T &版本,而不是T *。 (在這個例子中是t)當我製作一個模板函數的非const版本時,它按預期工作。 (在這個例子中爲t2)VS2010和g ++ 4.6.2都會出現這種情況。推廣到const規則是不同的,還是這是某種錯誤。爲什麼我的重載模板函數提升爲不同的const,然後是非模板函數。
#include <iostream>
using namespace std;
int f(const int&x){return 1;}
int f(const int*x){return 2;}
template <class T> int t(const T &x){return 3;}
template <class T> int t(const T *x){return 4;}
template <class T> int t2(T &x){return 5;}
template <class T> int t2(T *x){return 6;}
int main(int argc, char ** argv){
int x=0;
cout<<f(x)<<endl;
cout<<f(&x)<<endl;
cout<<t(x)<<endl;
cout<<t(&x)<<endl;
cout<<t2(x)<<endl;
cout<<t2(&x)<<endl;
return 0;
}
輸出是
1
2
3
3
5
6
更多解釋:t((const int *)&x)按預期工作。 – 2012-01-01 19:51:27
+1,用於一個簡短的完整測試用例。 – 2012-01-01 19:51:37