Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overload operator% for two doubles

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

like image 855
Jonas Avatar asked Jan 20 '23 21:01

Jonas


1 Answers

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.

like image 62
Johannes Schaub - litb Avatar answered Jan 29 '23 09:01

Johannes Schaub - litb