Trying to find a "simple to use" safe_bool idiom/implementation, I've ended up with my own.
Q: Is this implementation correct?
template <typename T>
class safe_bool
{
protected:
typedef void (safe_bool::*bool_type)() const;
bool_type to_bool_type(bool b) const
{ return b ? &safe_bool<T>::safe_bool_true : 0; }
private:
void safe_bool_true() const {}
private:
bool operator ==(safe_bool<T> const & rhs);
bool operator !=(safe_bool<T> const & rhs);
};
to be used like this:
struct A : public safe_bool<A>
{
// operator bool() const { return true; }
operator bool_type() const { return to_bool_type(true); }
};
The only addition to existing base classes would be to_bool_type
, but I hope I've got everything else correct, too.
The test cases I used (VC9) can be found here.
The downsides I see in implementation: bool_type
and to_bool_type
are visible in derived classes, which might not appease to everyone. Also, using the wrong template argument (e.g. class B : public safe_bool<A>
introduced during copy-and-paste) will go unnoticed.