过载解析中的常量/非常量右值引用
const/non-const rvalue reference in overload resolution
#include <iostream>
#include <string>
using namespace std;
void func(string &&a) { cout << "#1" << endl; }
void func(const string &&a) { cout << "#2" << endl; }
void func(int &&a) { cout << "#3" << endl; }
void func(const int &&a) { cout << "#4" << endl; }
int main()
{
func(string("1")); // call func(string &&)
func((const string)string("1")); // call func(const string &&)
func(1); // call func(int &&)
func((const int)1); // call func(int &&) not func(const int &&)
return 0;
}
从C++标准:
标准转换序列 S1 是比 标准转换序列 S2
如果...
S1 和 S2 是引用绑定 (8.5.3),以及 参考文献引用是相同的类型,除了顶级CV限定符, 并且 S2 初始化的引用所指的类型更多 符合 cv 标准,而不是引用由 S1 初始化的类型 指。
似乎最后一个调用的行为不符合预期。谁能为我解释?
(const int)1
的类型在过载解决之前调整为int
。
[EXPR]/6:
如果 prvalue 最初具有类型"cv
T
",其中T
是cv非限定的非类、非数组类型,则表达式的类型将在任何进一步分析之前调整为T
。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- OpenGL大的3D纹理(>2GB)非常慢
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 使用常量键但非常量值进行映射
- 为什么`is_open()`非常常量
- 从getter方法返回常量和非常量值
- 阻止const类函数在引用成员上调用非常常量类函数
- C++初始化非常大的常量数组,最佳实践
- 提高c++中非常大的常量的可读性