What is correct way to initialize a static member of type 'T &' in a templated class?

自作多情 提交于 2019-12-01 20:12:44

You can't, since you don't have a concrete instance. You can need to create an actual instance that you can refer to:

template <class T>
class singleton {
    ...
private:
    static T instance_;
public:
    static T& instance;
};
template <class T> T singleton<T>::instance_;
template <class T> T& singleton<T>::instance = singleton<T>::instance;

Or, more simply, just ditch the reference altogether:

template <class T>
class singleton {
    ...
public:
    static T instance;
};
template <class T> T singleton<T>::instance;

Off-the-sleeve: change instance to be of type 'T' instead of 'T &'.

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