class foo : public singleton<foo> { };
在这个过程中我学到了很多东西,但我现在陷入了困境,因为它破坏了我的VisualStudio2008链接器。问题在于静态实例成员和/或其初始化。
template<class T>
class singleton {
singleton();
singleton(singleton const &);
singleton & operator = (singleton const &);
public:
static T & instance;
};
template<class T> T & T::instance;
如有任何见解,将不胜感激!
编辑:
使用此类声明。。。
template<class T>
class singleton {
singleton();
singleton(singleton const &);
singleton & operator = (singleton const &);
public:
static T instance;
};
template <class T> T singleton<T>::instance;
foo类:公共单身人士<foo>{};
错误C2248:“singleton::singleton”
此诊断发生在编译器生成的函数“foo::foo(void)”中
我的解释是singleton想要构造一个foo对象,通过继承,它依赖于构造构造函数为私有的singleton。我以为singleton可以访问它自己的构造函数,但我想不是。有什么想法吗?
singleton<T>
存在需要更改类以用作单例的问题。最后,我为我的单例类模板编写了以下代码。
template<typename T>
class singleton_wrapper {
singleton_wrapper();
singleton_wrapper(singleton_wrapper const &);
singleton_wrapper & operator = (singleton_wrapper const &);
static T instance;
template<typename T> friend T & singleton();
};
template<typename T> T singleton_wrapper<T>::instance;
template<typename T>
T & singleton() {
return singleton_wrapper<T>::instance;
}
对于课堂。。。
class foo {
public:
void bar() { }
};
…可以使用以下方法访问它的单个实例(在main()之前初始化):
singleton<foo>().bar();
再次感谢你的帮助,尤其是GMan。我对我在stack的第一次体验非常满意
溢流