How to defined constructor outside of template class [duplicate]

牧云@^-^@ 提交于 2019-12-12 18:27:31

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/21488744/how-to-defined-constructor-outside-of-template-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!