Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
xmllmx Avatar asked Jun 30 '14 12:06

xmllmx


1 Answers

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

like image 52
TemplateRex Avatar answered Oct 03 '22 17:10

TemplateRex