Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2003-11-27 16:33:10


Daryle Walker <darylew_at_[hidden]> writes:

> All of the operator helpers need the final type to provide a core routine.
> AFAIK, Peter's idiom is to use a pointer-to-member(-function) as the core
> Boolean routine; it can't be provided by a library.

What am I missing?

template <class T>
struct bool_testable
{
 private:
    struct impl { int x; };
    typedef int impl::*safe_bool;
 public:
    operator safe_bool() const
    {
        return !*static_cast<T const*>(this) ? 0 : &impl::x;
    }
};

struct X : bool_testable<X>
{
    bool operator!() const { return true; }
};

struct Y : bool_testable<Y>
{
    bool operator!() const { return false; }
};

int main()
{
    X x;
    Y y;
    if (x) { return 1; }
    
    if (y)
        return 0;
    
// if (x == true) return 1; // fails to compile
// if (x == y) return 1; // fails to compile
        
    return 0;
}

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

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