views:

93

answers:

1

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.

+3  A: 

Using a pointer to a member function as the bool alias is idiomatic, as you're doing here.

Your implementation looks correct for what is there, but slightly incomplete. See http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool

IMO safe_bool falls into the category of things which do more harm than good; ie the complexity and confusion introduced by this idiom along with the mental effort needed to understand it are greater than the intial problem it is intending to solve.

Terry Mahaffey
Thanks - this the link is actually where I started. I have a few doubts about their implementation, which is why I don't trust every iota there. what seems missing is preventing `operator==(safe_bool<T>)`- but in which case this would be necessary? ---- I'd agree with the complexity vs. usefulness rating, my attempt was to make it "hurt less".
peterchen