过载解析中的常量/非常量右值引用

const/non-const rvalue reference in overload resolution

本文关键字:常量 非常 引用      更新时间:2023-10-16
#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 最初具有类型"cvT",其中Tcv非限定的非类、非数组类型,则表达式的类型将在任何进一步分析之前调整为T