Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2002-03-22 09:36:52


> From: "Aleksey Gurtovoy" <agurtovoy_at_[hidden]>
> > Here's a version of 'operators<>' template that allows "lazy"
> > instantiation of complementing operators:
>
> What about operations on different types - Duration + Date =
> Date, etc?

Well, these are harder, and not only because they are assymetrical so you
cannot define them as member functions, but also because there might be
several instances of the same operators with different types, e.g. "Duration
+ Date", "Time + Date", etc. But, on the second thought, that's what
templates are for :),

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& operator+=(int);
};

int main()
{
    my<int> m1;
    my<int> m2;

    // ...

    m1 + 5;
    5 + m1;

    // m1 * 5; // error

    return 0;
}

Aleksey


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