gpt4 book ai didi

c++ - operator== 的两个操作数的隐式转换

转载 作者:可可西里 更新时间:2023-11-01 15:23:55 25 4
gpt4 key购买 nike

即使没有定义相等运算符,以下代码也可以编译和执行而不会出错:

class A {
public:
operator bool() const { return true; }
};


int main()
{
A a, b;
a == b; //why does this compile?
return 0;
}

a == b 内部发生的事情是 operator bool() const 被调用用于both 操作数,然后两个比较 bool 值是否相等(这发生在我们的生产代码中,其中 class A 是一个智能指针类型,并给出了语义上可疑的结果)。

我的问题是:在这种情况下,C++ 标准中的什么规则允许隐式转换两个 操作数?我可以理解 一个 操作数将被隐式转换为 bool 以测试是否相等 if 另一个操作数已经是 bool,但不能两者兼而有之。

最佳答案

I can understand that one operand would be implicitly converted ..., but not both

那你误会了。编辑:根据评论专家的说法,参数相关查找似乎是您的假设正确的情况。但是你的情况不是 ADL。

What rule in the C++ standard allows for the implicit conversion of both operands

来自标准草案:

[over.match] (2.9)

  • Then the best viable function is selected based on the implicit conversion sequences (13.3.3.1) neededto match each argument to the corresponding parameter of each viable function.

我强调“每个论点”。不是“一个论点”。

关于c++ - operator== 的两个操作数的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41826412/

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