2

addition for a user defined type was defined by operator+, but += does not resolve to it, why?

typedef std::array<std::uint64_t,4> myvec_t;

inline myvec_t operator+(myvec_t foo, myvec_t bar){return mod_add(foo,bar);}

myvec_t a,b; 
a+=b; // g++ says: error: no viable overloaded '+='

EDIT: several people sufficiently answered the narrow question, I will accept an answer which explains why did the standard allow people to overload '+='(a,b) to do something different from a=a+b ?

14
  • 10
    The += operator is a separate operator, it's not + followed by assignment. Nov 8, 2019 at 11:36
  • 4
    In fact, for binary arithmetic operators (like +) this canonical implementations reference says that one should implement the operator through the combined assignment operator. That is your operator+ should use operator+= in its implementation. Nov 8, 2019 at 11:39
  • 1
    @ArneJ Still, how will that operator have an affect on the topic at hand?
    – Ted Lyngmo
    Nov 8, 2019 at 11:45
  • 2
    @Kostas What do you mean by "why did the standard allow this at all?" Allow what? Do you mean that it allows a += b to do something different from a = a + b? Then the standard doesn't really allow it, but it also doesn't forbid it. If you as the programmer want += do do something different from + followed by = then that's up to you. It's bad and will lead to confusion, but it's up to you. C++ doesn't hinder you in doing what you want, and if you want to shoot yourself in the foot then (again) it's up to you. Nov 8, 2019 at 11:57
  • 1
    @Kostas why not allow it? In += you can reuse existing memory instead of creating a new object and assigning it to this, while + doesn't need to return myvec_t (i.e. string builder like pattern).
    – Dan M.
    Nov 8, 2019 at 11:59

2 Answers 2

1

You declare/define an overload for operator+ and pass and return copies:

inline myvec_t operator+(myvec_t foo, myvec_t bar){return mod_add(foo,bar);}

you want to overload operator+= and pass and return references (assuming mod_add returns its result):

inline myvec_t& operator+=(myvec_t& foo, const myvec_t& bar)
{
    foo = mod_add(foo, bar);
    return foo;
}
0
0

Because you didn't proved an overload for operator+=, you provided an overaload for operator+

operator+= overaload is done with

inline myvec_t& operator+=(myvec_t& foo, const myvec_t& bar)
{
   foo = mod_add(foo,bar);
   return foo;
}

Note that your operator+ implementation is very inefficent because it copies both operand and return a copy of the object while should make 1 only copy in total (the latter).

1
  • Explain downvlote please
    – Moia
    Nov 8, 2019 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.