为什么显式bool()转换在上下文转换中发生 [英] Why doesn't explicit bool() conversion happen in contextual conversion

查看:115
本文介绍了为什么显式bool()转换在上下文转换中发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果以下测试程序

#include <iostream>

class A {
public:
    A() {}
    explicit operator bool() const {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return true;
    }
//    explicit operator bool() {
//        std::cout << __PRETTY_FUNCTION__ << std::endl;
//        return true;
//    }
    const operator int() const {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return 1;
    }
    operator int() {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return 1;
    }
};

int main() {
    A a;
    if (a) {
        std::cout << "bool()" << std::endl;
    }
    if (a + 0) {
        std::cout << "int()" << std::endl;
    }
}

运行,输出为

int A::operator int()
bool()
int A::operator int()
int()

而不是

bool A::operator _Bool()
bool()
int A::operator int()
int()

我期望的(如果你取消注释注释的部分,你会得到什么)。

what I expected (and what you get if you uncomment the commented parts).

因此,问题是转换为非const-int优先于转换为const-bool的规则是什么?

So the question is what are the rules giving the conversion to non-const-int precedence over converting to const-bool?

推荐答案

对参考绑定执行重载解析时,首选cv限定类型较少。这在13.3.3.2p3中讨论,其中给出了示例:

When performing overload resolution on a reference binding, the less cv-qualified type is preferred. This is discussed in 13.3.3.2p3, with the example given:

struct X {
  void f() const;
  void f();
};
void g(const X& a, X b) {
  a.f(); // calls X::f() const
  b.f(); // calls X::f()
}

注意,将一个对象绑定到成员函数的隐式对象参数(13.3.1.1.1p2)是引用绑定(13.3.3.1.4)。

Note that binding an object to the implicit object parameter of a member function (13.3.1.1.1p2) is a reference binding (13.3.3.1.4).

转换运算符被视为成员函数.1.5),用于过载分辨率(13.3p2)。上下文转换为 bool 具有初始化的语义(4p4)。

Conversion operators are treated as member functions (13.3.1.5) for the purposes of overload resolution (13.3p2). Contextual conversion to bool has the semantics of initialization (4p4).

重要的是,返回类型只考虑之后考虑转换运算符本身之间的重载解析(13.3.3p1)。

Importantly, any conversion required on the return type of the conversion operator is considered only after considering overload resolution between the conversion operators themselves (13.3.3p1).

解决方案是确保所有转换运算符都有相同的 const - 限额,特别是对标量类型。

The solution is to ensure that all conversion operators have the same const-qualification, especially to scalar type.

这篇关于为什么显式bool()转换在上下文转换中发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆