Safe bool idiom in boost?

Viewed 2486

Does the boost library provide an implementation of a safe bool idiom, so that I could derive my class from it?

If yes - where is it?

If no - what are my alternatives beyond implementing it myself?


I found the following similar question: " Is there a safe bool idiom helper in boost? " and the accepted answer suggests using bool_testable<> in Boost.Operators.

Unfortunately, when I checked the boost manual I couldn't find it there. Code using it fails to compile too.

I also stumbled on another SO question " Was boost::bool_testable<> relocated or removed? " and the comment there suggests that the bool_testable actually never made to any release version of the boost.

There is also an interesting article by Bjorn Karlsson on the subject which contains a code which could be copy-pasted into my project. I am hoping however, that there is a commonly accepted and maintained utility library (e.g. boost) that implements that already.


For compatibility reasons, I do not want to rely on C++11.

2 Answers

Since Boost 1.55 there is <boost/core/explicit_operator_bool.hpp> header in Boost.Core. It requires from you to define bool operator!() and use BOOST_EXPLICIT_OPERATOR_BOOL() macro (there are also variants of it BOOST_EXPLICIT_OPERATOR_BOOL_NOEXCEPT() and BOOST_CONSTEXPR_EXPLICIT_OPERATOR_BOOL()).

The documentation has an example:

template< typename T >
class my_ptr
{
    T* m_p;

public:
    BOOST_EXPLICIT_OPERATOR_BOOL()

    bool operator!() const
    {
        return !m_p;
    }
};
Related