Boost logo

Boost :

Subject: [boost] safe-bool CRTP class
From: Krzysztof Czainski (1czajnik_at_[hidden])
Date: 2011-05-27 10:02:18


Vladimir Batov prepared a safebool helper class as part of his Pimpl
library. I quote his rationale:

/// An implicit conversion to bool (operator bool() const) is very much
/// idiomatic and is often deployed in constructs like "if (foo)" and "if
/// (with no explicit op!() defined). However, sadly, implementing "operator
/// is *wrong* as that conversion kicks in far too often and unexpectedly.
Like in
/// "foo == 1", "foo+1", "1+foo" or potentially during
/// (if there are no op>>() and op<<() defined). Consequently, that
/// conversion to bool" functionality has to be implemented in an indirect
/// somewhat awkward way via an implicit conversion to some other type. The
/// type for the purpose appears to be a pointer to a member function. For
/// see the chapter 7.7 in Alexandrescu's "Modern C++ Design" and the
article at
/// by Bjorn Karlsson.

In the review of Pimpl Joej Falcou suggested to make safebool a CRTP base

I had prepared such a class some time ego, and I've been using it for a
while now. Is there interest in adding it to boost? Perhaps as part of the
operators library?

 * CRTP class, that provides operator unspecified_bool_t() const,
implemented in terms of
 * Derived::operator!
template < class Derived, class Base = empty_t >
class boolable : public Base
void unspecified_bool_t_f() {}

typedef void (boolable::*unspecified_bool_t)();


operator unspecified_bool_t() const
 return ! static_cast<Derived const&>( *this ) ? 0 :

struct X : public boolable<X>
  bool operator!() const { return condition; }
  // inherit operator unspecified_bool_t implemented in terms of the above


Boost list run by bdawes at, gregod at, cpdaniel at, john at