8

I get linker error if I define constructor\destructor of template class outside the class. Is it not allowed? I use Visual studio 2010.

error 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Tree::~Tree(void)" (??1?$Tree@H@@QAE@XZ) referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Tree::Tree(void)" (??0?$Tree@H@@QAE@XZ) referenced in function _main

In .h file

template <class T>
class Tree{
public:
    Tree(void);
    ~Tree(void);
    T x;
};

in .cpp file

#include "Tree.h"

template <class T> Tree<T>::Tree(void){
}

template <class T> Tree<T>::~Tree(void){
}

in main.cpp file

#include "Tree.h"
int main(){
    Tree<int> t;
    return 0;
}
Coder777
  • 985
  • 2
  • 9
  • 15
  • see: http://stackoverflow.com/questions/5612791/c-template-and-header-files – sellsword Jan 31 '14 at 19:48
  • If you really want to have a separate file you can put it in a .cpp file and #include that .cpp file in the header. But you have to exclude it from the build then! – Micka Jan 31 '14 at 20:08
  • The proposed solutions are not exhaustive, sorry to be late. In particular, if you want to allow the Tree's clients to use only specific types you can just explicit instantiate the template in the Tree.cpp file as `template class Tree;`. Doing so you instantiate the template for `int` so `main.cpp` can use the `Tree` template with `int` and nothing else. Very useful as per my daily uses. – fiorentinoing Oct 23 '20 at 07:13

1 Answers1

6

Templates need to be declared and implemented in the file you include. You cannot separate template class declaration and implementation and then only include the header file.

With templates, the class is not compiled until it's used. So there is no such thing as a compiled template class that can be linked against. Each time you use a template, it has to be compiled for a different type. And since the compiler does not have access to the implementation, it does not know how to compile it...

W.B.
  • 5,445
  • 19
  • 29