Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2002-03-22 12:47:23


David Abrahams wrote:
> What about the symmetry of implicit conversions? That's the usual
> argument given for implementing binary operators as free (friend)
> functions...

With the "2.01" version, it just works:

    template< typename T >
    struct operators
    {
    private:
        T& self() { return static_cast<T&>(*this); }
        T const& self() const { return static_cast<T const&>(*this); }

    protected:
        // ...
        T operator+(T const& other) { return T(self()) += other; }

        // ...
        template<typename U> friend T operator+(T x, U const& y) { return x
+= y; }
        template<typename U> friend T operator+(U const& y, T x) { return x
+= y; }
    };

    template< typename T >
    class my
        : public operators< my<T> > // note public inheritance
    {
        typedef operators< my<T> > ops;

    public:
        using ops::operator+;
        // ...
        my();
        my(int);
        
        my& operator+=(my const&);
    };

    int main()
    {
        my<int> m1;

        m1 + 5;
        5 + m1; // here!
    }

Aleksey


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