How to fix a purported lack of an “explicit instantiation declaration” when compiling a CRTP Singleton with Clang?

自闭症网瘾萝莉.ら 提交于 2019-12-05 08:21:58

I would recommend this implementation of a singleton instead:

template<class T>
struct SingletonBase {
    static T& get_instance() {
        static T instance;
        return instance;
    }
};

It's thread safe and remove your warning.

If you want, you can keep your create_singleton_instance:

template<class T>
struct SingletonBase {
    static T& get_instance() {
        static T instance{T::create_singleton_instance()};
        return instance;
    }
};

And changing the function implementation to:

static SomeClass create_singleton_instance() {
    return {};
}
R Sahu

The simplest fix is to define instance_ in SingletonBase.hh:

template < class T > class SingletonBase {
public:
  static T * get_instance() {
    if ( ! instance_ ) {
      instance_ = T::create_singleton_instance();
    }
    return instance_;
  }
private:
  static T * instance_;
};

template <typename T>
T* SingletonBase<T>::instance_ = nullptr;

However, I don't see the point of SingletonBase if you are going to rely on T::create_singleton_instance() to create the instance. You might as well implement get_instance() in the derived class.

Using a CRTP to implement the singleton pattern makes sense only if the base class can construct an instance of the derived class using the default constructor.

template < class T > class SingletonBase {
   public:
      static T& get_instance() {
         static T instance_;
         return instance_;
      }
   private:
};

Further reading: How to implement multithread safe singleton in C++11 without using <mutex>

Apparently, the explicit instantiation declaration should be of the form

template <> Singleton * SingletonBase< Singleton >::instance_;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!