Overloading operator% for floating types

爱⌒轻易说出口 提交于 2019-12-18 06:57:39

问题


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 floats.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!