【发布时间】:2015-01-15 13:29:12
【问题描述】:
我正在尝试使用静态成员实现模板类。从模板类派生的类无需编写额外代码即可实例化。
这是我幼稚(但并不成功)的方法:
Singleton.h:
template <class T> class Singleton {
protected:
Singleton();
static T instance_;
}
// explicit instantiation of 'instance_' ???,
// where 'instance_' is an instance of the derived class
template <class T> T Singleton<T>::instance_;
ConcreteA.h:
class ConcreteA : public Singleton<ConcreteA> {
public:
ConcreteA();
void foo();
}
main.c:
int main() {
// an instance of ConcreteA should have been created (no extra code)!!!
return 0;
}
有没有办法通过从Singleton 派生ConcreteA 来强制实例化ConcreteA,而无需编写额外的实例化代码?
一个肮脏的解决方法是在ConcreteA构造函数中调用instance_上的方法,例如:
混凝土A.c
ConcrereA::ConcreteA { instance_.foo(); }
有更好的解决方法吗?
【问题讨论】:
标签: c++ templates c++11 inheritance singleton