派生类中的显式模板静态成员实例化 [英] Explicit template static member instantiation in a derived class
问题描述
我试图用静态成员实现一个模板类。
I am trying to implement a template class with a static member. Classes that are derived from the template class shall be instantiated without the need to write extra code.
这是我天真的(而不是成功的)方法:
Here is my naive (and not successful) approach:
Singleton.h:
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:
ConcreteA.h:
class ConcreteA : public Singleton<ConcreteA> {
public:
ConcreteA();
void foo();
}
main.c:
main.c:
int main() {
// an instance of ConcreteA should have been created (no extra code)!!!
return 0;
}
有办法强制实例化<$ c $通过从 Singleton
中导出 ConcreteA
,无需编写额外的实例化代码,
Is there a way to force the instantiation of ConcreteA
by just deriving ConcreteA
from Singleton
, without writing extra instantiation code?
脏办法是调用实例_
ConcreteA
构造函数,例如:
A dirty workaround is to call an method on instance_
in the ConcreteA
constructor, for example:
ConcreteA.c
$ b
ConcreteA.c
ConcrereA::ConcreteA { instance_.foo(); }
有更好的解决方法吗?
推荐答案
基于自己的诡计,这适用于我测试的所有编译器,并且不需要在派生类构造函数中的任何代码: p>
Building upon your own "dirty trick", this works in all the compilers I tested, and doesn't require any code in the derived class constructor:
#include <iostream>
template <class T> class Singleton {
protected:
Singleton() { instptr_ = &instance_; }
static T instance_;
private:
static T* instptr_;
};
template<class T> T Singleton<T>::instance_;
template<class T> T* Singleton<T>::instptr_;
class ConcreteA : public Singleton<ConcreteA> {
public:
ConcreteA() { std::cout << "ConcreteA constructed.\n"; }
void foo();
};
int main() {
//Prints 'ConcreteA constructed.'.
return 0;
}
我的理解是取地址实例_
odr使用,强制它成立。我必须说,我不是100%肯定这是保证不会被优化在一些编译器的未来版本(我测试它与 -O2
无处不在)。
My understanding of it is that taking the address of instance_
odr-uses it, forcing it into existence. I must say I'm not 100% sure this is guaranteed not to be optimized away in future versions of some compiler (I tested it with -O2
everywhere).
编辑:看起来甚至写这样的基类构造函数
Looks like even writing the base class constructor like this
Singleton() { (void)&instance_; }
就足够了,可以除去 instptr _
这篇关于派生类中的显式模板静态成员实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!