Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If the following test-programm

#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;
    }
}

is run, the output is

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

and not

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

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

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

like image 300
wimalopaan Avatar asked Feb 27 '14 09:02

wimalopaan


2 Answers

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.

like image 123
ecatmur Avatar answered Sep 18 '22 06:09

ecatmur


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<const A&>(a).operator bool() ) {

Instead, what happens is this :

if ( a.operator int() )
like image 23
BЈовић Avatar answered Sep 20 '22 06:09

BЈовић