I'm currently using the following simple singleton class:
template<class T>
class singleton
: boost::noncopyable
{
public:
static T& get_instance()
{
assert(sm_instance != nullptr);
return *static_cast<T*>(sm_instance);
}
protected:
singleton()
{
assert(sm_instance == nullptr);
sm_instance = this;
}
virtual ~singleton()
{
assert(sm_instance != nullptr);
sm_instance = nullptr;
}
private:
static singleton<T>* sm_instance;
};
template<class T> singleton<T>* singleton<T>::sm_instance = nullptr;
class example_one
: public singleton<example_one>
{
static example_one instance;
};
example_one example_one::instance;
class example_two
: singleton<example_two>
{
static example_two instance;
};
example_two example_two::instance;
// Usage:
example_one& x = example_one::get_instance();
example_two& y = example_two::get_instance(); // not accessible because 'example_two' uses 'private' to inherit from 'singleton<T>'
However, I would like to tweak some things. I don't like that get_instance()
is inherited to the derivative class.
I would like to do something like this (non-working code):
template<class T>
T& get_singleton();
template<class T>
class singleton
{
friend T& get_singleton()
{
assert(sm_instance != nullptr);
return *static_cast<T*>(sm_instance);
}
}
// Usage:
example_two& x = get_singleton<example_two>();