|
Boost : |
From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2002-03-22 14:36:51
Daniel Frey wrote:
> The problem is a semantic one: Do I really want to use all of the
> operators as they are defined by operators<>? Sometimes, you
> might want lots of them, but replace a special one with a
> user-supplied version (to provide an optimized version for special
> operators or when mixing types). But generally, I think we're on
> the right way. For member-functions (member-operators), you can
> write your own version in the derived class, it's only a problem for
> the friend-operators, as you cannot override them.
How about this:
template< typename T >
struct operators
{
private:
T& self() { return static_cast<T&>(*this); }
T const& self() const { return static_cast<T const&>(*this); }
private:
template<typename U> static T do_add(T x, U const& y) { return x += y; }
protected:
// ...
T operator+(T const& other) { return T(self()) += other; }
// ...
template<typename U> friend T operator+(T& x, U const& y) { return
x.do_add(x,y); }
template<typename U> friend T operator+(U const& y, T& x) { return
x.do_add(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&);
private: friend class operators< my<T> >;
static my do_add(my const& x, int y); // optimized implementation
};
int main()
{
my<int> m1;
m1 + 5;
5 + m1;
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