Search code examples
c++c++11booleantype-conversionexplicit-conversion

Why is my "explicit operator bool()" not called?


#include <iostream>

using namespace std;

struct A
{
    explicit operator bool() const
    {
        return true;
    }

    operator int()
    {
        return 0;
    }
};

int main()
{
    if (A())
    {
        cout << "true" << endl;
    }
    else
    {
        cout << "false" << endl;
    }
}

My expectation was that A() would be contextually converted to bool using my operator bool(), and therefore print true.

However, the output is false, showing that operator int() was invoked instead.

Why is my explicit operator bool not called as expected?


Solution

  • Because A() is not const, the operator int() is selected. Just add const to the other conversion operator and it works:

    #include <iostream>
    
    using namespace std;
    
    struct A
    {
        explicit operator bool() const
        {
            std::cout << "bool: ";
            return true;
        }
    
        operator int() const
        {
            std::cout << "int: ";
            return 0;
        }
    };
    
    int main()
    {
        if (A())
        {
            cout << "true" << endl;
        }
        else
        {
            cout << "false" << endl;
        }
    }
    

    Live Example that prints: "bool: true" and without the const it prints "int: false"

    Alternatively, make a named constant:

    // operator int() without const
    
    int main()
    {
        auto const a = A();
    
        if (a)
        // as before
    }
    

    Live Example that prints "bool: true".