0

Possible Duplicate:
Why do I get “unresolved external symbol” errors when using templates?

I'm trying to implement a generic Queue using templates.

I have the following code in my header:

template<class Item>
class Queue{
protected:
    struct linked_list;
    int size;
public:
    Queue();
    Queue(Item T);
};

I have a Queue.cpp:

template<class Item>
Queue<Item>::Queue()
{

}
template<class Item>
Queue<Item>::Queue(Item T)
{

}

but every time I compile, I get a linker error because of unresolved externals.

I reinstalled VS2012 twice (thinking the linker was broken), but the problem keeps appearing.

I read that there is some problem with the function implementations being in a separate file when working with templates, but I haven't seen any solution except putting the implementation in the header.

Is there a more elegant way to do so?

Community
  • 1
  • 1
Moshe Magnes
  • 393
  • 2
  • 9

2 Answers2

2

Template doesn't support a definition is provided elsewhere and creates a reference (for the linker to resolve) to that definition

You need to use the inclusion model, put all Queue.cpp definition into Queue.h file. Or in the bottom of Queue.h

#include "Queue.cpp"
billz
  • 44,644
  • 9
  • 83
  • 100
0

Template declarations must be included in your source code in their entirety. If you want to split them, one way I prefer to use is:

on the bottom of queue.h:

#define QUEUE_H_IMPL
#include "queue_impl.h"

and in queue_impl.h

//include guard of your choice, eg:
#pragma once

#ifndef QUEUE_H_IMPL
#error Do not include queue_impl.h directly. Include queue.h instead.
#endif

//optional (beacuse I dont like keeping superfluous macro defs)
#undef QUEUE_H_IMPL

//code which was in queue.cpp goes here

Actually now after I've looked at it you don't need an include guard at all if you #undef QUEUE_H_IMPL.

Andrei Tita
  • 1,226
  • 10
  • 13