Chebz
Chebz

Reputation: 1395

Linker error with template class

I am trying to implement particle system using my custom template linked list class and getting linker error:

Error   3   error LNK2019: unresolved external symbol "public: struct Node<class Particle> * __thiscall LinkedList<class Particle>::Pop(void)" (?Pop@?$LinkedList@VParticle@@@@QAEPAU?$Node@VParticle@@@@XZ) referenced in function "private: void __thiscall ParticleEmitter::addParticles(void)" (?addParticles@ParticleEmitter@@AAEXXZ)*

Here is the Node.h:

template <class T>
struct Node
{
    Node(const T&);
    ~Node();
    T* value;
    Node* previous;
    Node* next;
};

Here is the addParticle code:

LinkedList<Particle> freeParticles; //definition in ParticleEmitter.h

void ParticleEmitter::addParticles(void)
{
    int numParticles = RandomGetInt(minParticles, maxParticles);

    for (int i = 0; i < numParticles && !freeParticles.IsEmpty(); i++)
    {
        // grab a particle from the freeParticles queue, and Initialize it.

        Node<Particle> *n = freeParticles.Pop();
        n->value->init(color, 
            position, 
            direction * RandomGetFloat(velMin, velMax), 
            RandomGetFloat(lifetimeMin, lifetimeMax));
    }

}

And here is the Pop function:

//Pop from back
template <class T>
Node<T>* LinkedList<T>::Pop()
{   
    if (IsEmpty()) return NULL;

    Node<T>* node = last;
    last = last->previous;

    if (last != NULL) 
    {
        last->next = NULL;
        if (last->previous == NULL) head = last;
    }
    else head = NULL;

    node->previous = NULL;
    node->next = NULL;

    return node;
}

I am writing all of the code from scratch so maybe I made a mistake somewhere and I am new to templates too.

Upvotes: 1

Views: 179

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Did you define your Pop function in a source(e.g. .cpp) file, rather than the header file? You can't do it that way with templates. You need to provide the function definitions in the header files. The definition needs to be visible at the point of instantiation.

Upvotes: 3

Related Questions