Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to defined constructor outside of template class [duplicate]

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;
}
like image 601
Coder777 Avatar asked Jan 31 '14 19:01

Coder777


1 Answers

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...

like image 82
W.B. Avatar answered Sep 27 '22 22:09

W.B.