Boost logo

Boost :

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


Hello,

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
(!foo)"
/// (with no explicit op!() defined). However, sadly, implementing "operator
bool()"
/// is *wrong* as that conversion kicks in far too often and unexpectedly.
Like in
/// "foo == 1", "foo+1", "1+foo" or potentially during
lexical_cast<string>(foo)
/// (if there are no op>>() and op<<() defined). Consequently, that
"implicit
/// conversion to bool" functionality has to be implemented in an indirect
and
/// somewhat awkward way via an implicit conversion to some other type. The
best
/// type for the purpose appears to be a pointer to a member function. For
more
/// see the chapter 7.7 in Alexandrescu's "Modern C++ Design" and the
article at
/// http://www.artima.com/cppsource/safebool.%e2%80%8bhtml by Bjorn Karlsson.

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

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)();

public:

operator unspecified_bool_t() const
{
 return ! static_cast<Derived const&>( *this ) ? 0 :
&boolable::unspecified_bool_t_f;
}
};

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

Regards,
Kris


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk