Contextually Converted to Bool -- Chris Sharpe

A nice writeup of when this "it just works the way you expect" feature kicks in:

Contextually converted to bool

by Chris Sharpe

From the article:

Something I found mildly surprising about C++11 is that this works:

#include <iostream>

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

int main()
{
    Testable t;
    if (t)
        std::cout << "Converted to true!\n";
}

That is, it compiles and prints Converted to true!.

The new bit here is the explicit keyword. When I first saw an example like this, I expected to have to write

if (bool( t )) // ...

[...]

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.