我有一个可以正常工作的重载函数。 (示例中的 f)。当我将它转换为同一事物的模板版本时,它总是调用 T& 版本而中断,从不调用 T*。 (示例中的 t)当我制作模板函数的非常量版本时,它按预期工作。 (示例中的 t2)这发生在 VS2010 和 g++ 4.6.2 中。对 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
最佳答案
你的 int x
不是 const
.所以&x
产生 int*
.以下是两个候选函数:
-
int t<int*>(T const&)
(相当于int t<int*>(int * const&)
)<-- T 是int*
;需要 0 次转化 -
int t<int>(T const*)
(相当于int t<int>(int const*)
)<-- T 是int
;需要从int*
进行转换至int const*
选择更好的匹配,即没有转换的匹配。这是引用版本。
关于c++ - 为什么我的重载模板函数以不同于非模板函数的方式提升为 const。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8695112/