为浮动类型重载operator%

r3d*_*ice 3 c++ templates g++

我试图重载运算符%因为你不能在双类型上使用模数,

float a = 5.0; 
float b = 5.0;
a  = a % b;
// not allowed
Run Code Online (Sandbox Code Playgroud)

我试图用这种函数重载运算符%:

template <>
MyClass*                MyClass<float>::operator%(Myclass &other)
Run Code Online (Sandbox Code Playgroud)

对于其他涉及浮动的操作,我使用:

template <class T>
MyClass*                MyClass<T>::operator%(MyClass &other)
Run Code Online (Sandbox Code Playgroud)

它从来没有编译实际上我被卡住了,无法找到绕过这个问题的方法,g ++仍然警告我你不能对浮点数执行模数,我的模板语法有问题或者它真的不可能.

Mat*_*Mat 6

您不能按照您希望它的工作方式重载原始类型的运算符.

对于C++ 11 draft n3290,§13.5 运算符重载,第6点:

运算符函数应该是非静态成员函数或者是非成员函数,并且至少有一个参数,其类型是类,对类的引用,枚举或对枚举的引用.[...]

原始类型不是类(或枚举),因此它们不能具有成员函数.并且您无法创建全局,float operator%(float&,float&)因为它不涉及参数列表中的类或枚举.(另请参阅C++ FAQ 26.10"我可以定义一个与内置/内部/基本类型一起使用的运算符重载吗?".)
您需要%表达式中至少有一个术语是用户定义的类型.

你可以创建一个类Float并定义要在其上的任何操作,但你不能a = a % b;,如果既使用功能abfloat秒.

或者您可以#include <cmath>使用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;
}
Run Code Online (Sandbox Code Playgroud)

使用自定义"浮动包装器"的简单示例(不完整,可能不太安全,但可以让您入门):

#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;
}
Run Code Online (Sandbox Code Playgroud)