模板化重载运算符的编译错误 "No global operator found"

Compile error "No global operator found" for templated overloaded operator

我已经定义了一个模板 class 和重载运算符。编译时,我收到以下错误消息:

error C2677: binary '+=' : no global operator found which takes type 'Class' (or there is no acceptable conversion)

这里是class的相关代码:

template<int foo>
class Class
{
private:
    int value;
public:
    template<int other_foo>
    friend class Class;

    // Constructors and copy constructors for several data type 
    // including other possibilities of "foo"; all tested.

    Class& operator+=(const Class& x)
    {
        value += x.value;
        return *this;
    }
    template<class T>
    Class& operator+=(const T& x)
    {
        this += Class(x);
        return *this;
    }
};

如果我创建两个对象,例如 Class<3>operator += 工作正常并且做正确的事。

但是,如果我有一个 Class<3> 的对象和 Class<2> 的一个对象,我会得到上面的错误,它指向为 T [的构造函数定义了“+=”的行foo 的不同值工作正常并且也经过测试]。

我做错了什么?我该如何解决这个错误? 运算符已定义,就在上面几行。

假设必要的构造函数确实存在并且可以正常工作,那么您发布的代码中的错误是

this += Class(x);

它试图修改不可变指针的值this。应该是

*this += Class(x);

我认为有两个问题,都在这一行:

this += Class(x);

一:添加的对象应该是*this而不是this,因为后者是指针,不是对象本身

二:没有从TClass的转换构造函数。也就是说,您无法从 Class<3> 转换为 Class<2>,因此 Class(x) 将无法编译。解决方案是添加它:

template<int other> Class(const Class<other> &o)
{}