gpt4 book ai didi

c++ - 为什么选择转换运算符的这种重载?

转载 作者:行者123 更新时间:2023-12-02 15:03:39 25 4
gpt4 key购买 nike

考虑following code .

struct any
{
template <typename T>
operator T &&() const;

template <typename T>
operator T &() const;
};
int main()
{
int a = any{};
}

这里第二个转换运算符是由重载决策选择的。为什么?

据我了解,这两个运算符分别推导为 operator int &&() constoperator int &() const 。两者都在可行的函数集中。通读 [over.match.best] 并没有帮助我弄清楚为什么后者更好。

为什么后者的功能比前者更好?

最佳答案

返回 T& 的转换运算符是首选,因为它比返回 T&& 的转换运算符更专业。

参见 C++17 [temp.deduct.partial]/(3.2):

In the context of a call to a conversion function, the return types of the conversion function templates are used.

和/9:

If, for a given type, deduction succeeds in both directions (i.e., the types are identical after the transformations above) and both P and A were reference types (before being replaced with the type referred to above): — if the type from the argument template was an lvalue reference and the type from the parameter template was not, the parameter type is not considered to be at least as specialized as the argument type; ...

关于c++ - 为什么选择转换运算符的这种重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59142566/

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