2

So I am getting an unresolved external symbol error and I can't figure out why. All files exist in the same project and the compiler seems to be generating all the obj files. I am deriving from a template class so I am thinking maybe I am not declaring my derived methods properly. I am using the visual c++ compiler in VS 2012.

BaseClass.h

template<class T> class BaseClass
{
public:
    BaseClass() {}

    virtual ~BaseClass() {}

    void Foo();
}

BaseClass.cpp

#include "BaseClass.h"

template<class T> void BaseClass<T>::Foo()
{
    cout << "hello";
}

SomeClass.h

#include "BaseClass.h"

class SomeClass : public BaseClass<long>
{
    public:
       SomeClass() {}

       void DoSomething();
}

SomeClass.cpp

#include "SomeClass.h"

void SomeClass::DoSomething()
{
     Foo(); // link error
     this->Foo(); // also gives link error
     BaseClass<long>::Foo(); // also gives link error
}

So method DoSomething() can't seem to invoke anything from its base class due to link error. Is there something obvious here I am doing wrong?

SimpleGuy
  • 143
  • 5
  • Generic implementations of template methods need to be either in *.h or in *.inl that would be #include'ed at the end of *.h file. Implementation where you specify what your template class is need to go in *.cpp. – Yulia V Aug 24 '13 at 23:30
  • Thanks this was the solution. First time working with templates in c++, wasn't aware that template definitions had to be in header. – SimpleGuy Aug 25 '13 at 00:59

2 Answers2

2

When you create a template, the compiler creates a new class with the given template argument. Therefore, the compiler needs to have access to the implementation of the methods and it can't be linked in. So you can't separate the implantation into a .cpp file.

If you really want to separate your declarations from your implantation then you should look into .inl files. You can read more about them here.

Community
  • 1
  • 1
Caesar
  • 9,483
  • 8
  • 40
  • 66
1

When using a class with a template, you need to provide a definition in it's header file, not a separate .cpp file.

Franko Leon Tokalić
  • 1,457
  • 3
  • 22
  • 28