为什么我的重载模板函数提升为const的方式与非模板函数不同?

Why is my overloaded template function is promoting to const differently then a non-template function.

本文关键字:函数 方式 重载 我的 为什么 const      更新时间:2023-10-16

我有一个工作正常的重载函数。(例子中的f)。当我将它转换为相同东西的模板版本时,它总是调用T&版本,而不是T*。(在示例中)当我创建模板函数的非const版本时,它按预期工作。这在VS2010和g++ 4.6.2中都发生过。对const规则的提升是不同的,还是这是某种bug ?

#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 is int*;
  • int t<int>(T const*)(相当于int t<int>(int const*)) <——T is int;要求从int*转换为int const*

选择更好的匹配,即没有转换的匹配。这是参考版本

在这两种情况下:

cout<<t(x)<<endl;
cout<<t(&x)<<endl;

编译器正在选择template <class T> int t(const T &x)的过载,因为intint *分别可以满足T

在本例中:

cout<<t2(&x)<<endl;

没有选择template <class T> int t2(T &x)过载,因为它不能满足。不能将引用绑定到一个临时值(右值),&x是一个临时值