为什么我的重载模板函数提升为const的方式与非模板函数不同?
Why is my overloaded template function is promoting to const differently then a non-template function.
我有一个工作正常的重载函数。(例子中的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 isint*
; -
int t<int>(T const*)
(相当于int t<int>(int const*)
) <——T isint
;要求从int*
转换为int const*
选择更好的匹配,即没有转换的匹配。这是参考版本
在这两种情况下:
cout<<t(x)<<endl;
cout<<t(&x)<<endl;
编译器正在选择template <class T> int t(const T &x)
的过载,因为int
和int *
分别可以满足T
。
在本例中:
cout<<t2(&x)<<endl;
没有选择template <class T> int t2(T &x)
过载,因为它不能满足。不能将引用绑定到一个临时值(右值),&x
是一个临时值
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中将函数压缩为两种方式
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何编写具有相同名称的相同函数,该函数在C++中几乎以相似的方式处理不同的类参数?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?
- 用于基于成员字段或函数创建比较器的快捷方式
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 将uint8_t*buffer和size_tbufferlen从C++传递到C中的API函数的最佳方式是什么
- 我是否以错误的方式声明了getpriorityvalues函数
- 如何编写一个递归函数,以随机的方式混淆从0到6的数字
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 以编程方式在 C++ 中创建函数
- 将函数作为参数传递的两种方式之间的区别
- 程序按执行方式工作,直到我向其添加析构函数为止
- 在 C++ 中使用删除函数的不同方式
- 简单的计数和求和函数没有按照我预期的方式工作
- C++17 中函数参数的指针对齐方式
- 不同的构造函数方式