C++ singleton with policies

The traditional Singleton pattern only supports a default constructor (one that takes no arguments), but recently I needed to create a singleton from a class which required an integer argument in its constructor.

This can be solved quite elegantly with a policy-based design. Take a look at the following (non thread-safe!) implementation:

#ifndef SINGLETON_HPP
#define SINGLETON_HPP

// Creation policies
template<class T> struct CreateWithIntParameter
{
    static T* Create()
    {
        return new T(m_intParameter);
    }
    static const int m_intParameter;
};

// Non-thread-safe singleton
template <class T, template<class> class CreationPolicy>
class Singleton
{
public:
    static T& instance()
    {
        if (!m_instance)
        {
            m_instance = CreationPolicy<T>::Create();
        }
        return *m_instance;
    }
private:
    Singleton();
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);

    static T* m_instance;
};

template <class T, template<class> class C>
T* Singleton<T, C>::m_instance = 0;

#endif // SINGLETON_HPP

Here is a small example how to use it:

#include "singleton.hpp"
#include <iostream>

using namespace std;

class Foo
{
public:
    Foo(int a) : m_a(a)
    {
        cout << "Foo constructed" << endl;
    }
    void bar()
    {
        cout << "a = " << m_a << endl;
    }
private:
    Foo();
    int m_a;
};

template<> const int CreateWithIntParameter<Foo>::m_intParameter = 5;

typedef Singleton<Foo, CreateWithIntParameter> FooSingleton;

int main()
{
    FooSingleton::instance().bar();
    FooSingleton::instance().bar();
    return 0;
}

The output looks like this:

Foo constructed
a = 5
a = 5

One thought on “C++ singleton with policies”

  1. Nice implementation. I ran into a problem doing something similar:

    Sometimes when writing a library we might want to use a singleton and at the same time want internal library code to call methods of the singleton. Using policies, the user could make choices about the behavior or implementation of the library (thing performance trade-offs).

    If the user however determines the type of the singleton (using the policy) there is no elegant way I can think of how the internal library code can use that singleton because its type is unknown.

Leave a Reply