How to defined constructor outside of template class

11,247

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

Share:
11,247
Coder777
Author by

Coder777

Updated on June 28, 2022

Comments

  • Coder777
    Coder777 almost 2 years

    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;
    }