Reputation: 453
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 ?
Upvotes: 2
Views: 1267
Reputation: 2354
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).
Upvotes: 0
Reputation: 27577
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;
}
Upvotes: 1