Why doesn't explicit bool() conversion happen in contextual conversion

后端 未结 2 521
北海茫月
北海茫月 2021-01-01 18:11

If the following test-programm

#include 

class A {
public:
    A() {}
    explicit operator bool() const {
        std::cout << __PRE         


        
2条回答
  •  借酒劲吻你
    2021-01-01 18:25

    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()
    }
    

    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).

    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).

    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).

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

提交回复
热议问题