Templated NonCopyable Singleton class ?

Hi
i have the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <typename T>
class Singleton
{
  public:
    static T& GetInstance()
    {
      static T instance;
      return instance;
    }

  private:
    //Cant do this
    //Singleton(){};

}; 

class Foo : public Singleton<Foo>
{

};


I would like to make any class that inherits from Singleton non constructable as well (So that the only way to interact with it is by using the GetInstance() function), but the problem is that if i declare Singletons constructor as private then i get an error on line 7 where the static instance is being constructed :\

So i was just wondering if there is a way around this?

Last edited on
You can make Foo non-copyable by declaring the copy constructor and the copy assignment operator as deleted ...

1
2
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;

... but I don't think there is a way to disable the default constructor of the derived class from within the Singleton class.

The only way I can think of to accomplish what you want is to declare the constructor as private and make the Singleton a friend for each class.

1
2
3
4
5
6
class Foo : public Singleton<Foo>
{
private:
	Foo() {}
	friend Singleton<Foo>;
};
Last edited on
My terminology has always been a little casual, but wouldn't inherit of a singleton into more than one object be creation of multiples of the singleton, invalidating its contract? Granted the syntax lets you do whatever, but conceptually speaking, here...? Unless the singleton is static and shared across all the classes?
Last edited on
stav wrote:
i get an error on line 7

I apologize for adding a post in a thread that has already been marked as solved, but I think the problem on line 7 is related to what the method GetInstance() is required to return.
In the most common implementation of the (today often disapproved) singleton pattern, the so called 'Mayers singleton', GetInstance() returns an instance of the singleton class itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
// I think it is known as 'Mayer singleton':
class MySingleton{
public:
    static MySingleton& getInstance() {
        static MySingleton instance;
        return instance;
    }
private:
    MySingleton() = default;
    ~MySingleton() = default;
    MySingleton(const MySingleton&) = delete;
    MySingleton& operator=(const MySingleton&)= delete;
};


Anyway, as far as I know, the monostate pattern is often considered a good ‘replacement’ for the singleton one also because it’s easier to inherit.
And it is less criticized.
Topic archived. No new replies allowed.