C++ Op. overloading: More for less

Started by
5 comments, last by alvaro 13 years, 10 months ago
I thought I'd find this on Google, but no.

Let's assume we need to implement all mathematical ops for this.
class number { double mValue; public: };


More than likely, I would write many operators like * as...
number operator*(const number& r) { return number(*this) *= r; }


Outside of macros, is there a way to make most compilers interpret stuff like this without me having to type it?
Advertisement
1. Get someone else to write it
2. http://www.boost.org/doc/libs/1_43_0/libs/utility/operators.htm
3. Bite the bullet, unless you're doing this over and over I don't see how you'll save that much time.
Mmkay, thanks much.
class number{    double mValue;public:    template<typename T>    number operator*(const T& r)    {        return number(*this) *= r;    }    template<typename T>    number& operator*=(const T& r)    {        mValue *= r;        return *this;    }}


then u can implement special cases with:
template<>number& number::operator*=<int>(const int& r){    //special treatment    mValue *= r;    return *this;}

operator* should probably be a const member function:

number operator*(const number& r) const { return number(*this) *= r; }
Depending on the requirements, you can use the 'wrapped' type's operators by just providing a cast operator:
class number{  double mValue;public:  number(                 ) : mValue(        ) {}  number( double        v ) : mValue(v       ) {}  number( const number& n ) : mValue(n.mValue) {}  operator       double&()       { return mValue; }   operator const double&() const { return mValue; }};void test(){  number a = 0.5, b = 42;  number c = a*b;  number d = c;  d += a - b;}
Quote:Original post by Hodgman
Depending on the requirements, you can use the 'wrapped' type's operators by just providing a cast operator:*** Source Snippet Removed ***


My experience with that type of thing is ambiguities all over the place. But perhaps I didn't know what I was doing...

This topic is closed to new replies.

Advertisement