微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 操作符==的两个操作数的隐式转换

即使没有定义相等的运算符,下面的代码编译并执行没有错误
class A {
public:
    operator bool() const { return true; }
};


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

对于一个== b而言内部发生的是对两个操作数都调用了运算符bool()const,然后将两个布尔值进行比较,以相等(这发生在我们的生产代码中,类A是智能指针类型,并在语义上给出可疑的结果).

我的问题是:C标准中的什么规则允许在这种情况下两个操作数的隐式转换?我可以理解,如果另一个操作数已经是一个bool,而不是两个操作数,一个操作数将被隐式转换为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) needed
    to match each argument to the corresponding parameter of each viable function.

我强调“每个论据”.不是“单一论证”.

原文地址:https://www.jb51.cc/c/112352.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐