Boost logo

Boost :

Subject: Re: [boost] safe-bool CRTP class
From: Gregory Crosswhite (gcross_at_[hidden])
Date: 2011-05-27 12:22:00


On 5/27/11 7:02 AM, Krzysztof Czainski wrote:
> 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?

Hmm, I like the idea of insulating the user from having to construct a
fancy type to return a safe bool, but it is a little weird to have the
user implement the ! operator instead of the bool operator directly.
How about simply defining an as_bool method and having the user
implement that:

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 ).as_bool()
     ?&boolable::unspecified_bool_t_f
     : 0;
}

bool operator!() const
{
  return !(*this);
}

};

Usage:
struct X : public boolable<X>
{
   bool as_bool() const { return condition; }
};


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