Possible Duplicate:
Why can templates only be implemented in the header file?
I realise that there are already few topics like this on SO but I did not find any that would answer my problem.
I have already written my template singleton class using this tutorial http://www.codeproject.com/Articles/4750/Singleton-Pattern-A-review-and-analysis-of-existin
but unfortunately I keep on getting errors :
/home/USER/testcode/cpp_workshop/main.cpp:-1: error: undefined reference to `Singleton::Instance()' :-1: error: collect2: ld
my singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
template <typename T>
class Singleton
{
public:
static T& Instance();
protected:
virtual ~Singleton();
inline explicit Singleton();
private:
static T* _instance;
static T* CreateInstance();
};
template<typename T>
T* Singleton<T>::_instance = 0;
#endif // SINGLETON_H
singleton.cpp
#include "singleton.h"
#include <cstdlib>
template <typename T>
Singleton<T>::Singleton()
{
assert(Singleton::_instance == 0);
Singleton::_instance = static_cast<T*>(this);
}
template<typename T>
T& Singleton<T>::Instance()
{
if (Singleton::_instance == 0)
{
Singleton::_instance = CreateInstance();
}
return *(Singleton::_instance);
}
template<typename T>
inline T* Singleton<T>::CreateInstance()
{
return new T();
}
template<typename T>
Singleton<T>::~Singleton()
{
if(Singleton::_instance != 0)
{
delete Singleton::_instance;
}
Singleton::_instance = 0;
}
and that's how I call it (with normall - not templated or anything - class Game
)
Singleton<Game>::Instance().run();