is it possible to overload the 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 utilizing the possibility of implicit constructor calls of C++ to get around of this problem. I did it in the following way:
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 does not work! Any hints, ideas, ... are appreciated! Thanks in advance, Jonas
The reason this doesn't work is because overload resolution for user defined operator functions is only triggered if at least one operand of the expression has a class or enumeration type.
So you are out of luck. This won't work.
I think the best you could try is waiting for a C++0x compiler and instead of writing 3.14
, you write 3.14_myd
, as a user defined literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With