Hi all,
I've implemented my own singleton pattern using templates for my classes to derive from. Here is a very cut down version of my code:
Code:
// THIS FILE IS SINGLETON.H
template <typename T>
class Singleton
{
public:
static T* CreateSingleton( )
{
if (m_Instance == NULL)
m_Instance = new T ; // ERROR HERE
return m_Instance ;
}
private:
static T* m_Instance ;
};
// initialize instance to NULL
template<typename T>
T* Singleton<T>::m_Instance = NULL ;
the above is the singleton file, as I said it is only a snippet of the code.
This is how you derive from the singleton class
Code:
#include "Singleton.h"
class MyClass : public Singleton<MyClass>
{
};
And this is how you use it
Code:
#include "MyClass.h"
int main( )
{
MyClass* mc = MyClass::CreateSingleton( ) ;
return 0 ;
}
Now I have seen code like this all over the internet and people seem to be using it fine. However when I try to compile it in g++ I get an error in Singleton.h on the line that says
Code:
m_Instance = new T ;
The error is "undefined type MyClass". Now I completely understand this error because the singleton class is trying to "new" an instance of type T. However because I havent included "MyClass.h" at the top of "Singleton.h" it doesnt know about the class MyClass. For obvious reasons I dont want to add that to Singleton.h
Now im usually fine with this kind of stuff so im putting it down to im having a blonde day. But for the life of me I cannot find away around this problem, and whats more confusing is that other people are using this technique with no issues.
Thanks for any help