Boost logo

Boost :

From: Joel de Guzman (joel_at_[hidden])
Date: 2003-11-27 03:31:05


Nicola Musatti <nmusatti_at_[hidden]> wrote:
> Joel de Guzman wrote:
> [...]

>> Can you spot some problems with this too? The point is that it would be
>> nice to have one *correct* and generic implementation that everyone
>> can use. It's easy to get it wrong (I did). There are some subtle issues
>> that make it an ideal candidate for a small library component (e.g.
>> Borland does not like the pointer to member stuff, maybe there's a
>> better formulation for Borland? e.g. While the code above is fine with
>> g++3.2 and Comeau, VC7.1 does not like it in some cases, etc...).
>
> How about something like:
>
> template <typename T> class bool_convertible {
> public:
> typedef void (bool_convertible::* safe_bool )();
> protected:
> safe_bool make_safe_bool(bool cond) const {
> return cond ? &bool_convertible::dummy : 0;
> }
> private:
> void dummy() {}
> };
>
> To be used as:
>
> class A : public boost::bool_convertible<A>
> {
> public:
> A(int i) : a(i) {}
> operator safe_bool() const { return make_safe_bool(a != 0); }
> private:
> int a;
> };
>
> It has the drawback that class templates require a redefinition of the
> safe_bool typedef. I only made a very simple test, but it appears to be
> accepted by Borland 5.6.4 .

Pardon me, actually, Borland is ok with my previous posted code.
It's just that it doesn't like these code:

    if (x1 && x2)
        ...

    if (!x1)
        ...

Here's my test code:

    template <typename T>
    struct safe_bool
    {
        T* dummy;
        typedef T* safe_bool::*type;
    };

    template <typename T>
    inline typename safe_bool<T>::type
    make_safe_bool(bool cond)
    {
        return cond ? &safe_bool<T>::dummy : 0;
    }

    struct X
    {
        typedef safe_bool<X>::type safe_bool;
        operator safe_bool() const
        {
            return make_safe_bool<X>(true);
        }
    };

    struct Y
    {
        typedef safe_bool<Y>::type safe_bool;
        operator safe_bool() const
        {
            return make_safe_bool<Y>(true);
        }
    };

    void foo() {}

int
main()
{
    X x;
    if (x)
    {
        foo();
    }

    X x2;

    if (x && x2) // Borland does not like this
    {
        foo();
    }

    if (!x) // Borland does not like this
    {
        foo();
    }

// Y y;
// x == y; // must not compile
}

I believe your code also has the same problems with Borland?

-- 
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