可能重复:
Why should the implementation and the declaration of a template class be in the same header file?
我目前正在尝试实施单例模板。我直接从german Wikipedia获取了代码(您应该能够阅读代码)。但我总是在Visual C ++中得到一个奇怪的编译错误:
game.obj : error LNK2019: unresolved external symbol ""protected: __thiscall singleton<class game>::singleton<class game>(void)" (??0?$singleton@Vgame@@@@IAE@XZ)" in function ""protected: __thiscall game::game(void)" (??0game@@IAE@XZ)".
fatal error LNK1120: 1 unresolved externals.
(运行Visual Studio 2010)
除了在多个页面上拆分之外,我不知道我在代码中做错了什么。
我定义了一个模板类singleton
,它将由应该成为单例的类game
继承。
singleton.hpp:
template <class T_DERIVED>
class singleton {
public:
static T_DERIVED& get_instance();
protected:
singleton();
private:
singleton(const singleton&);
singleton& operator=(const singleton&);
};
singleton.cpp:
#include "singleton.hpp"
template <class T_DERIVED>
singleton<T_DERIVED>::singleton()
{
}
template <class T_DERIVED>
T_DERIVED& singleton<T_DERIVED>::get_instance()
{
static T_DERIVED instance;
return instance;
}
template <class T_DERIVED>
singleton<T_DERIVED>& singleton<T_DERIVED>::operator=(
const singleton<T_DERIVED>&)
{
return *this;
}
game.hpp:
#include "singleton.hpp"
class game: public singleton<game> {
friend class singleton<game>;
protected:
game();
};
game.cpp:
#include "game.hpp"
game::game()
{
}
main.cpp中:
#include "game.hpp"
#include <iostream>
int main()
{
game& a = game::get_instance();
return 0;
}
答案 0 :(得分:0)
模板方法定义必须可供该模板的最终用户使用。因此,它们(通常)应该在声明模板的头文件中。因此,将模板拆分为多个部分并将定义放入源(cpp)文件会导致链接器错误。