Search code examples
c++templatessingletoncrtpenable-if

Implementing a singleton wrapper class that also verifies 'the singleton constructor is private'


I made a singleton wrapper template class that provides the instance() member function and is also supposed to assert whether the singleton class has a private constructor. The definition is as follows:

template <
    class T,
    class = typename std::enable_if<!std::is_constructible<T>::value, void>::type
>
class singleton {
public:
    static T& instance() {
        static T inst;
        return inst;
    }
};

When I define a singleton class like:

class class_with_public_constr
 : public singleton<class_with_public_constr> {
public:
    class_with_public_constr() {}
    friend class singleton<class_with_public_constr>;
};

The code passes the enable_if assertion. What is wrong with my singleton class template?

Coliru


Solution

  • You can simplify the code as following and also get the error printed when the constructor is public (i.e. not private, protected)

    template<typename T>
    class singleton
    {
    public:
        // Below constructor is always invoked, because the wannabe singleton class will derive this class
        singleton () {
            static_assert(!std::is_constructible<T>::value, "the constructor is public");
        }
    
        static T& instance();
    };
    

    The client class will look like below:

    class A : public singleton<A> 
    {
      friend class singleton<A>;   
    //public:  // <---------- make it `public` & you get the error!
      A() {}
    };
    

    Here is the demo.