|
Boost : |
From: Joel de Guzman (joel_at_[hidden])
Date: 2003-11-27 18:09:03
David Abrahams <dave_at_[hidden]> wrote:
> 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;
> }
Indeed. A library solution is possible and better. The only thing
I do not like with the solution above is the inheritance, which implies
multi-inheritance when X or Y are already subclasses. Well, you can
chain the inheritance, but... The solution that I posted a while ago
doesn't require any inheritance at all.
-- Joel de Guzman http://www.boost-consulting.com http://spirit.sf.net
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk