-2

I have a class template A which looks like this:

A.h

template <typename T>
class A
{
  T data;

  public:
  A(void) { };
  ~A(void) { };

  void addItem(T d);
}

A.cpp

template <typename T>
void A<T>::addItem(T data)
{

};

And another class template B which looks like this:

B.h

#include "a.h"
class B : public A<int>
{
   public:
   B(void) : A<int>() {};
   ~B(void) {};

   void doSomething();
};

B.cpp

#include "B.h"

void B::doSomething()
{
   addItem(1);
}

When compiling this under VS 2012 I get an error which says:

error LNK2019: unresolved external symbol "public: void __thiscall A::addItem(int)" (?addItem@?$A@H@@QAEXH@Z) referenced in function "public: void __thiscall B::doSomething(void)" (?doSomething@B@@QAEXXZ)

Why isn't the addItem() member function resolvable? Can you please recommend a way to fix this?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
horatiu
  • 193
  • 2
  • 10

1 Answers1

2

You need to move the content of A.cpp into A.h since C++ is very finicky about templates not being defined in headers.

norlesh
  • 1,749
  • 11
  • 23
  • @jogojapan is the rewording more appropriate? – norlesh Jan 02 '14 at 01:57
  • 1
    @jogojapan cheers - have a good day 7;^) – norlesh Jan 02 '14 at 01:58
  • 1
    C++ couldn't care less whether you define your function templates in headers or not. It just wants a definition in each translation unit, which is pretty reasonable when you consider that template instantiation is performed during compilation, not linking. – Lightness Races in Orbit Jan 02 '14 at 02:03
  • @Lightness Races in Orbit, would you like to explain to the question poster what constitutes a translation unit? – norlesh Jan 02 '14 at 02:05
  • @LightnessRacesinOrbit I see where your coming from, I just feel it appropriate to word the answer to the level of the question – norlesh Jan 02 '14 at 02:20
  • I feel it appropriate not to coddle site contributors. He will encounter terms he doesn't recognise all throughout his career, and now is a perfect time to learn to go and research them. Not to mention the topic is _fully_ covered on the two duplicates linked in the question's comments... – Lightness Races in Orbit Jan 02 '14 at 02:21