More C++ Idioms/Safe bool

= Safe Bool =

Intent
To provide boolean tests for a class but restricting it from taking participation in unwanted expressions.

Motivation
User provided boolean conversion functions can cause more harm than benefit because it allows them to participate in expressions you would not ideally want them to. If a simple conversion operator is defined then two or more objects of unrelated classes can be compared. Type safety is compromised. For example,

Solution and Sample Code
Safe bool idiom allows syntactical convenience of testing using an intuitive if statement but at the same time prevents unintended statements unknowingly getting compiled in. Here is the code for the safe bool idiom.

Reusable Solution

There are two plausible solutions: Using a base class with a virtual function for the actual logic, or a base class that knows which function to call on the derived class. As virtual functions come at a cost (especially if the class you're augmenting with Boolean tests doesn't contain any other virtual functions). See both versions below: Here's how to use safe_bool: In C++, address of protected members functions can't be taken in a derived class. Derived class could be a standard class, a class template or a specialization of a class template. Some implementations of safe bool idiom declare safe_bool_base::this_type_does_not_support_comparisons as protected, address of which can't be taken in the derived class - a requirement in reusable safe bool idiom.

An insightful discussion on the boost mailing list initiated by Krzysztof Czainski resulted in an implementation of safe bool idiom using CRTP as well as another using macros.

C++11
The C++11 standard provides explicit conversion operators as a parallel to explicit constructors. This new feature solves the problem in a clean way.