Singleton模板不在Visual C++中编译
Singleton Template does not compile in Visual C++
可能重复:
为什么模板类的实现和声明应该在同一个头文件中?
我目前正在尝试实现一个单例模板。我直接从德语维基百科上获取了代码(你应该能够阅读代码(。但我在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
,它将由应该成为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;
}
模板方法定义必须对该模板的最终用户可用。因此,它们(通常(应该在声明模板的头文件中。因此,将模板拆分为多个部分并将定义放入源(cpp(文件会导致链接器错误。