gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:08:23 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com