I'm working on a Vector2D class, and I think both vector addition and scalar addition make sense to be implemented with the +=/+ operators.
Trouble is, I don't really know how to work around this apparent argument ambiguity, here's what Clang says:
vector2d_test.cpp:17:16: error: use of overloaded operator
'+=' is ambiguous (with operand types 'Vector2D<float>' and 'int')
vector += 1;
~~~~~~ ^ ~~~~~~~
vector2d.hpp:34:18: note: candidate function
Vector2D<T>& operator+=(const Vector2D<T>& other)
^
vector2d.hpp:41:18: note: candidate function
Vector2D<T>& operator+=(const T summand) const
Here are the two functions:
Vector2D<T>& operator+=(const Vector2D<T>& other)
{
x += other.x;
y += other.y;
return *this;
}
template <typename S>
Vector2D<T>& operator+=(const S summand) const
{
x += summand;
y += summand;
return *this;
}
So... any idea what I can do about this?
Easiest way is to define the functions inside Vector2D ala:
Notes:
friend
s, which allows them to be defined conveniently inlineconst
(one was in your question)T
isfloat
thenint
s will work just fine unless you do something funny like giveVector2D
an implicit constructor from a singleint
that makes the choice of conversion ambiguousIt's not clear what you're trying to do. The
operator+=
functions you post aren't legal unless they are members. And if they are members, and you have something like:the
Vector2D<float>::operator+=( Vector2D<float> const& )
function isn't callable, and so there can be no ambiguity. If the functions aren't members, then they should be written:Even in this case, the first cannot be called with an
rhs
of typeint
, so there is no ambiguity.EDIT:
I missed the
const
at the end of the second in your posting. This is an obvious typo on your part, It still doesn't change anything, unless you also have some implicit conversions toVector2D
(which is probably not a good idea); otherwise, the first version is still not callable. If there is, for example, an implicit conversion fromint
toVector2D
, and you call+=
on a non-const Vector2D, then the first overload is a better match for the implicit first argument (which results in thethis
pointer), since it is an exact match, without even a cv conversion, but the second function is a better match for the second argument, because the template instantiation results in an exact match. So the call is ambiguous.You have all written in you error message. You tried to add to your vector variable of int type, but your vector has floats. It should be:
or
Take a look. When you have this vector:
function corresponding to this vector has header:
Second one doesn't matter right now. And when you try to add to your vector 1, you are trying to invoke function:
Which you didn't declare. That's why compiler message you an error - it can't find proper function.