Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ basic template question

I'm slightly confused with template specialization.

I have classes Vector2, Vector3 which have operator+= in it (which are defined the following way).

   Vector2& operator+=(const Vector2& v) {

      x() += v.x(), y() += v.y();

      return *this;
   }

Now I want to add the generic addition behaviour and say something like:

template <typename V> const V operator+(const V& v1, const V& v2) {
   return V(v1) += v2;
}

This compiles fine and works for both Vector2 and Vector3. But let's say I want to have a slightly more efficient "+" operation for my Vector2 and I want it to act the following way (using the template specialization):

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

This looks fine to me, but unfortunately placing these two chunks of code right after each other makes the code fail the compilation

(linker says error LNK2005: "Vector2 const operator+<Vector2>(Vector2 const &,Vector2 const &)" (??$?HVVector2@core@lf@@@core@lf@@YA?BVVector2@01@ABV201@0@Z) already defined in ...)

What is my error and where did I go wrong?

Thank you.

like image 560
Yippie-Ki-Yay Avatar asked Dec 13 '22 20:12

Yippie-Ki-Yay


1 Answers

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.

like image 57
Mike Seymour Avatar answered Dec 26 '22 00:12

Mike Seymour