bastibe
bastibe

Reputation: 17189

Can't link to class with templates using Visual C++

I wrote a nice little array class in C++ that uses void* to save its entries.

Now, I want make it use templates. This is my new header:

template <typename T>
class SimpleArray
{
public:
    SimpleArray();
    ~SimpleArray();

    void SetEntry(int idx, T setEntry);
    T GetEntry(int idx);
    // and so on
protected:
    T *pData
    short iNumEntries;
}

The functions are implemented in a different file like this:

#include "SimpleArray.h"

template <typename T>
void SimpleArray<T>::SetEntry(int idx, T setEntry)
{
    // code here
}

template <typename T>
T SimpleArray<T>::GetEntry(int idx)
{
    // more code here
}

This compiles fine, but when I want to use it in some other code like this

SimpleArray<SomeType*> cache;
cache.SetEntry(0, someThing);

I get a linker error stating that there is an unresolved external symbol

2>Thing.obj : error LNK2019: unresolved external symbol "public: bool __thiscall SimpleArray::SetEntry(int,class someThing *)" (?SetEntry@?$SimpleArray@PAUsHandle@@@@QAE_NHPAUsHandle@@@Z) referenced in function "public: void __thiscall Thing::Function(int)" (?DelEntry@Thing@@QAEXH@Z)

Man, I hate it that the linker does not even try to say anything intelligible.
Anyway, the real trouble is that I did something wrong here to upset the linker.

Could you tell me what I did wrong?

Upvotes: 1

Views: 348

Answers (2)

unquiet mind
unquiet mind

Reputation: 1112

You need to put all the code in the header file. C++ does not effectively support separate compilation of templates.

Upvotes: 7

wilhelmtell
wilhelmtell

Reputation: 58667

Place the template in the header. You can't separate C++ template definitions from their instantiations.

Upvotes: 3

Related Questions