Review: reusable safe_bool implementation
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 b开发者_JAVA百科ool() 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.
The “wrong template argument” problem you mentioned is almost completely eliminated by the static_cast
in the wikibooks.org solution (“for testability without virtual functions”) cited by @Terry Mahaffey. The only thing I can see wrong with their solution is the separate safe_bool_base
class, which will suppress the empty base optimization when it appears in multiple base classes (or elements in a compressed_pair
). Personally, I'd move that implementation back up into the template.
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.
精彩评论