问题
I'm trying to overload the operator % because you can't use modulus on double types,
float a = 5.0;
float b = 5.0;
a = a % b;
// not allowed
I Was trying to overload the operator % with this kind of function :
template <>
MyClass* MyClass<float>::operator%(Myclass &other)
For other operation non involving float I use :
template <class T>
MyClass* MyClass<T>::operator%(MyClass &other)
It never compiled actually I'm stuck and can't find a way to bypass this problem, g++ is still warning me that you can't perform modulo on floats, is something wrong with my template syntax or is it really impossible.
回答1:
You can't overload operators for primitive types the way you'd want it to work.
For C++11 draft n3290, §13.5 Operator Overloads, point 6:
An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration. [...]
Primitive types aren't classes (or enums), so they can't have member functions. And you can't create a global float operator%(float&,float&)
since that doesn't involve a class or enum in the parameter list. (See also C++FAQ 26.10 "Can I define an operator overload that works with built-in / intrinsic / primitive types?".)
You need at least one of the terms in the %
expression to be a user-defined type.
You could create a class Float
and define whatever operations you want on it, but you cannot get a = a % b;
to use your function if both a
and b
are float
s.
Or you could #include <cmath>
and use std::fmod
:
#include <iostream>
#include <cmath>
int main()
{
float a = 13.0f;
float b = 5.0f;
a = std::fmod(a, b);
std::cout << a << std::endl;
return 0;
}
Simple example with a custom "float wrapper" (incomplete, probably not quite safe as-is, but can get you started):
#include <iostream>
#include <cmath>
class Float {
private:
float val;
public:
Float(float f): val(f) {};
Float operator%(Float const& other) const {
return std::fmod(val, other.val);
}
Float operator%(float const& other) const {
return std::fmod(val, other);
}
// conversion operator could be handy
operator float() { return val; }
};
int main()
{
Float a = 13.0f;
Float b = 5.0f;
Float c = a % b;
std::cout << c << std::endl;
// this also works
Float d = 13.0f;
float e = 5.0f;
float f = d % e;
std::cout << f << std::endl;
return 0;
}
来源:https://stackoverflow.com/questions/9201497/overloading-operator-for-floating-types