1
template<typename Type>
class List
{
public:
    List(void);
    ~List(void);
...
}

which inherited by

template<typename Type>
class LinkedList : public List<Type>
{
public:
    LinkedList(void);
    ~LinkedList(void);
...
}

but when I

List<int>* list = new LinkedList<int>();

there comes error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::LinkedList<int>(void)" (??0?$LinkedList@H@@QAE@XZ) referenced in function _wmain

I know that for template, the type is determined when compiling, I feel it should be ok to determine typename Type when compiling and then determine the derived class type at runtime. Is it possible to use polymorphism with template class in this way?

////////////////////////////////////////////////////////////////////////////////

Thank hkaiser and Chubsdad, it is the linking problem. I defined the constructor in the cpp file, but somehow the linker cannot detect it. And I tried to move it to the header file, it worked, but I don't like that. It seems to be ok if I define the functions in cpp with a resolved type, like:

LinkedList<int>::LinkedList(void)
    :List<int>()
{
    mHead = new Node<int>(0);
}

instead of:

template<typename Type>
LinkedList<Type>::LinkedList(void)
    :List<Type>()
{
    mHead = new Node<Type>(0);
}

But what's the difference? Why it becomes invisible with the template defination while visible with a resolved one? Is it possible to define template member functions in cpp?

HeliumYi
  • 13
  • 4

4 Answers4

2

The error is generated by the linker because you did not define the constructor for the LinkedList class. Or it is not visible to the compiler at the point where you use the type LinkedList<int> as shown above.

hkaiser
  • 11,403
  • 1
  • 30
  • 35
1

where is the definition of the constructors and the destructors? The linker is complaining about that.

This also may be helpful

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
0

I ran into same problem, broken up the header file into two. First header file declared base template class, second included cpp implementation and then derived classes. I rather have one more header file than implementation in it or implementing ~20 methods for every type.

Brejlounek
  • 33
  • 3
0

Well, it seems an old problem, a tricky decleration in cpp can solve this:

template LinkedList<int>::LinkedList(void);

It's a compromise to avoid definition in .h files, but you must declare for each used type. A simple solution is to define the function in .h files, or, according to http://www.parashift.com/c++-faq-lite/templates.html[35.14], there's a seemingly controversial solution to use the keyword export. This is the helpful question: Storing C++ template function definitions in a .CPP file

Community
  • 1
  • 1
HeliumYi
  • 13
  • 4