views:

133

answers:

3
+7  A: 

If the specialisation is in a header file, then you need to declare it inline to allow it to be included in more than one compilation unit.

Note that you don't actually need a template specialisation here; a simple overload will do the same thing.

Mike Seymour
An overload would always be a better alternative.
David Rodríguez - dribeas
+4  A: 

put this

template<> const Vector2 operator+(const Vector2& v1, const Vector2& v2);

in your header file and

template<> const Vector2 operator+(const Vector2& v1, const Vector2& v2) {
   return Vector2(v1.x() + v2.x(), v1.y() + v2.y());
}

in a .cpp file.

AOI Karasu
That's likely to be less efficient than defining it inline in the header file.
Mike Seymour
+3  A: 

I am not really sure you want to follow that path. The operator+ that you have defined as a template will match any and all types, possibly creating conflicts. Why don't you provide a simple non-templated operator+ for each of your vectors?

There are also other style issues:

Vector2& operator+=(const Vector2& v) {
   x() += v.x(); // you don't need operator, here and it might
                 // be confusing if you don't have operator, priorities clear
   y() += v.y();
   return *this;
}

Also:

// This should not be a template!!!
template <typename V> const V operator+(V v1, const V& v2) {
   return v1 += v2;
}

In some circumstances the compiler can elide the copy if operator+ is defined as above (if the first argument is a temporary), while it cannot elide the copy with your definition.

The problem with the operator+ as you have defined is that the compiler will try to use it with any type:

struct non_sumable {};
int main() {
   non_sumable a,b;
   a + b;           // matches the template, tries to instantiate
                    // compiler error says that non_sumable does not 
                    // have operator+=, which might be confusing
}
David Rodríguez - dribeas