C ++% overload operator for two pairs

Is it possible to overload operator% for two doubles?

 const double operator%(const double& lhs, const double& rhs) { return fmod(lhs, rhs); } 

Of course, this generates an error, because one of the two parameters must have a class type. So I thought about using the C ++ constructor implicit invocation feature to get around this problem. I did it as follows:

 class MyDouble { public: MyDouble(double val) : val_(val) {} ~MyDouble() {} double val() const { return val_; } private: double val_; }; const double operator%(const MyDouble& lhs, const double& rhs) { return fmod(lhs.val(), rhs); } const double operator%(const double& lhs, const MyDouble& rhs) { return fmod(lhs, rhs.val()); } 

... and:

 double a = 15.3; double b = 6.7; double res = a % b; // hopefully calling operator%(const MyDouble&, const double) using a implicit constructor call 

Unfortunately this will not work! Any hints, ideas, ... appreciated! Thanks in advance, Jonas

+4
source share
2 answers

The reason this does not work is because overload resolution for user-defined operator functions is only triggered if at least one operand of the expression has an enumeration class or type.

So you are out of luck. This will not work.

I think the best thing you could try is to wait for the C ++ 0x compiler, and instead of writing 3.14 you write 3.14_myd as a user literal.

+9
source

alternatively, double MyDouble::operator%(const double&) const; , eg:

 #include <iostream> #include <cmath> class t_double { public: t_double(const double& val) : d_val(val) { } t_double(const t_double& other) : d_val(other.d_val) { } ~t_double() { } const double& val() const { return this->d_val; } double operator%(const double& rhs) const { return fmod(this->val(), rhs); } double operator%(const t_double& rhs) const { return fmod(this->val(), rhs.val()); } private: double d_val; }; int main(int argc, char* const argv[]) { const t_double a(15.3); const t_double b(6.7); std::cout << a % b << " == " << a.val() << " % " << b.val() << "\n"; return 0; } 
0
source

All Articles