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

后端 未结 2 625
北海茫月
北海茫月 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:26

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

    Using const member function of a non-const object, requires conversion of a non-const object into const-object. That is why operator int() has a better match over operator bool() const.

    To make it a bit clearer, if you would remove int operators, what really happens with the first bool context (first if) is this :

    if ( const_cast(a).operator bool() ) {
    

    Instead, what happens is this :

    if ( a.operator int() )
    

提交回复
热议问题