开发者

C++ Overload operator% for two doubles

开发者 https://www.devze.com 2023-03-01 12:14 出处:网络
is it possible to overload the operator% for two doubles? const double operator%(const double& lhs, const double& rhs)

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 o开发者_运维百科perator%(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.


alternatively, implement double MyDouble::operator%(const double&) const;, like so:

#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

精彩评论

暂无评论...
验证码 换一张
取 消