C++11 – Contextually Converted to bool
In C++, a one-argument constructor can implicitly be used to convert some source value or object into an instance of your class.
To prevent this you can mark your one-argument constructors as explicit. In that case, if you want the conversion you have to explicitly perform the casting.
C++11 adds this functionality to conversion operators as well, however, its behavior surprised me.
For example:
#include <iostream>
using namespace std;
class Foo
{
public:
explicit operator bool() const { return true; }
};
int main()
{
Foo f;
if (f)
{
cout << "f is true" << endl;
}
return 0;
}
The output of this piece of code is “f is true”.
In other words, the compiler is implicitly converting f into a Boolean, even though the conversion operator is marked as explicit.
This surprised me. I immediately blamed it on a compiler bug. However, after some more investigation, it turns out the C++ standard has this notion of “contextually converted to bool”.
The C++ standard has a paragraph explaining this behavior, section 4 Standard conversions [conv]
3 An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t (8.5).
4 Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (8.5).
Searching through the standard, an expression can be contextually converted to bool in several cases, not only in the above if-statement.
I also found this blog post explaining this behavior.



