Running % on doubles?

closed account (Dy7SLyTq)
im writing my own version of Bajarne Stroustrop's calculator, and i want to add % to the operators it can use. my only issue is doubles can't use modulo. i thought this would be no issue; i could just overload the operator. so i wrote this:
1
2
3
4
5
6
7
8
9
10
11
double operator%(double LValue, double RValue)
{
     int CLValue, CRValue;

     CLValue = LValue;
     CRValue = RValue;

     CLValue %= CRValue;

     return (double) (CLValue);
}


but got this:
test.cpp:95:47: error: ‘double& operator%(double, double)’ must have an argument of class or enumerated type


short of writing a class to emulate double, is there a quick and easy hack around this?
Last edited on
Even if the C++ would allow to overload operators for fundamental types your code is invalid because the operator calls itself recursively

1
2
3
4
5
6
7
8
9
double& operator%(double LValue, double RValue)
{
     int CLValue, CRValue;

     CLValue = LValue;
     CRValue = RValue;

     return (double) (CLValue % CRValue); // here it calls itself recursively
}


Moreover you are trying to return a reference to a local temporary expression.
Last edited on
closed account (Dy7SLyTq)
1) i didnt mean to have the & there. thanks for pointing it out.
2) sorry my mistake. ill make it so it doesnt call it recursively.
Oh, I am wrong. It does not call itself recursively. You are calling operator % for integers.

By the way C# applies operator % for doubles. For example 3.2 % 2 will be equal to 1.2.
closed account (Dy7SLyTq)
good to know. and wait it doesnt? i thought that () had higher precedence than &, causing it to do the conversion first.
The casting was applied to int expression (CLValue % CRValue). So it has nothing with the operator % for doubles.
closed account (Dy7SLyTq)
ah ok thanks. but anyways, is there a way to do this without writing a class?
naraku9333 + 1
Thank you.
Topic archived. No new replies allowed.