c++ - 为什么我的重载模板函数以不同于非模板函数的方式提升为 const。

标签 c++ templates overloading

我有一个可以正常工作的重载函数。 (示例中的 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/

相关文章:

c++ - 使用函数模板重载运算符

wpf - 加载控件后立即启动模板动画

C++函数模板部分特化?

java - 方法重载如何决定在以下情况下调用哪个版本的重载方法

java - 在Java中是否可以在不使用反射的情况下从不同的非子类调用 protected 方法?

c++ - 变量的前向声明?

C++编译问题;类方法

c++ - 为什么当我声明和定义一个不带参数的构造函数和一个带参数的构造函数时编译器会报错?

c++ - 模板中类的构造函数

c++ - 使用 C 预处理器指令建立 GCC/G++ 链接