3

I've defined a template class and overloaded operators. When compiling, I get the following error message:

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

Here is the relevant code of the 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;
    }
};

If I create two objects of, e.g., Class<3>; the operator += works fine and does the right thing.

However, if I have an object of Class<3> and one of Class<2>, I get the above error which points at the line where "+=" is defined for T [the constructor for different value of foo works fine and is also tested].

What am I doing wrong? How can I resolve this error? The operator is defined, just a few lines above.

2 Answers 2

3

Assuming that the necessary constructor does indeed exist and work correctly, the error in the code you've posted is

this += Class(x);

which tries to modify the value of the immutable pointer this. It should be

*this += Class(x);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That was the problem.
1

I think that there are two problems, both in this line:

this += Class(x);

One: the object added to should be *this instead of this, because the latter is a pointer, not the object itself.

Two: There is no conversion constructor from T to Class. That is, you cannot convert from Class<3> to Class<2> so the Class(x) will not compile. The solution would be to add it:

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

1 Comment

Thanks! It now works. Thanks for the comment with the constructor from T to Class; this was already done but not included in my code snippet to not have a long code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.