Search code examples
c++implicit-conversionoverload-resolution

Why is the conversion to int used, not to bool?


I implemented two conversions for a class. One is to bool, one is to int&.

If I implicitly convert to int, it uses the int& conversion, but if I want a bool, it still uses the int& conversion.

struct A
{
    operator bool() const;
    operator int&();
};

// trying to call these:
A a;
int  i_test = a; // calls operator int&()
bool b_test = a; // calls operator int&()

I understand that a is implicitly converted to int& and then to bool, but why does it take that longer path? How can I avoid it without having to write a.operator bool()?


Solution

  • A a; declares a non-const object. Since the conversion function is a member function, it accepts an implicit this pointer that points at a. And overload resolution will choose the non-const qualified member, since it is called on a non-const object.

    The fact that it was a conversion to bool that triggered overload resolution is a bit of a red herring. The function's return type (int& or bool) only makes them candidates for overload resolution (because these will work for converting to bool), but it isn't enough to determine the outcome of overload resolution itself.