c++ - 重载决策中的 const/non-const 右值引用

标签 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++ 标准:

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if
...
S1 and S2 are reference bindings (8.5.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.

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

最佳答案

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

[expr]/6 :

If a prvalue initially has the type “cv T”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

关于c++ - 重载决策中的 const/non-const 右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46015090/

相关文章:

c++ - 可以自动刷新QTableWidget吗?

c++ - 在命名成员函数重载解析期间,什么时候 'this' 不在范围内?

c++ - 右值引用的直接实例化是否定义了行为?

c++ - 引用重载,而不是唯一的按值传递+ std::move?

c++ - Boost 程序选项和 "one of"关系

c++ - dll 中的 vector.h 在我的应用程序中不可用

python - 为什么在类上定义 __getitem__ 使其在 python 中可迭代?

c++ - const T& 与 T&&

c++ - 使用内部类型作为模板参数继承模板类

c++ - 为什么编译器可以通过引用传递和值传递来重载函数