Jump to content
  • Advertisement
Sign in to follow this  
zyrolasting

C++ Op. overloading: More for less

This topic is 2914 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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


Share this post


Link to post
Share on other sites
operator* should probably be a const member function:

number operator*(const number& r) const { return number(*this) *= r; }

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!