I implemeted a template singleton class along with static member definition:
template <typename T> class SingletonT
{
public:
static T *GetInstance()
{
if (!s_instance)
{
s_instance = new T;
}
return s_instance;
}
private:
static T *s_instance;
};
template <typename T> T *SingletonT<T>::s_instance = 0;
It compiles fine and works fine.
Now, I'm trying to create a singleton that will use custom function instead of operator new
:
template <typename T, T *(*f)()> class PolymorphSingletonT
{
public:
static T *GetInstance()
{
if (!s_instance)
{
s_instance = f();
}
return s_instance;
}
private:
static T *s_instance;
};
template <typename T, T *(*f)()> T *PolymorphSingletonT<T, T *(*f)()>::s_instance = 0;
I get a compile error on the last line saying error C2146: syntax error : missing ')' before identifier 'f'
I use MSVC2005 compiler.
Update Now I ended up with functor approach:
template <typename T, typename F> class PolymorphSingletonT
{
public:
static T *GetInstance()
{
if (!s_instance)
{
s_instance = F::Create();
}
return s_instance;
}
private:
static T *s_instance;
};
template <typename T, typename F> T *PolymorphSingletonT<T, F>::s_instance = 0;
However, it forces me to wrap my creation function with a functor. It only adds a couple of code lines and works perfectly, but anyway I'm still interested in getting it without functors.