xmllmx
xmllmx

Reputation: 42379

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?

Upvotes: 9

Views: 3427

Answers (1)

TemplateRex
TemplateRex

Reputation: 70556

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

Upvotes: 18

Related Questions