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.
I do not know of a commonly accepted utility library that provides the safe-bool idiom. There have been a few attempts within Boost, and they often result in debates about how to provide a safe-bool implementation (naming conventions, macros, inline includes, inheritance). As a result, there are at least three implementations existing within Boost, with only one of the implementations, Boost.Spirit.Classic’s safe_bool, designed for external use.
Details and concepts for each implementation:
operator boost::range_detail::safe_bool< MemberPtr >::unspecified_bool_type() constmember function that delegates to the staticsafe_bool::to_unspecified_bool()function.boost/detail/workaround.hppbefore includingsmart_ptr/detail/operator.hpp.this_typetype.Ttype.T* pxmember variable.boost::spirit::class::safe_boolto be used without mandating multiple inheritance on the derived class.boost::spirit::classic::safe_bool< Derived >. IfDerivedalready inherits fromBase, then useboost::spirit::classic::safe_bool< Derived, Base >.bool operator_bool() constmember function.This example uses Boost 1.50. Each class should evaluate to true in boolean context if the integer passed to the constructor is greater than 0:
Resulting output:
I do not know of any alternatives. When I have ran across safe-bool idioms, most of the implementations have been a copy-and-paste variants of the implementation provided in Bjorn Karlsson’s article.