重载决策中的const /非const rvalue引用

时间:2017-09-02 15:00:54

标签: c++ overloading rvalue-reference

#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-qualified比S1初始化的引用类型   指。

似乎最后一次调用没有按预期运行。谁能为我解释一下?

1 个答案:

答案 0 :(得分:1)

在重载解析之前,(const int)1的类型会调整为int

[expr]/6

  

如果prvalue最初的类型为“ cv T”,其中T是一个cv非合格的非类非数组类型,其类型为在进行任何进一步分析之前,将表达式调整为T