我正在尝试使用CRTPed基础来保存一些静态初始化代码,如下所示:
template <typename T>
class InitCRTP
{
public:
static InitHelper<T> init;
};
template <typename T> InitHelper<T> InitCRTP<T>::init;
现在,任何需要在InitHelper<T>
中完成工作的班级都可以这样做:
class WantInit : public InitCRTP<WantInit>
{
public:
void dummy(){init;}//To force instantiation of init
};
template class InitCRTP<WantInit>;//Forcing instantiation of init through explicit instantiation of `InitCRTP<WantInit>`.
要强制InitCRTP<WantInit>::init
实例化,我可以使用dummy
或使用显式实例化,如上所示。有没有办法解决这个问题,两者都没有?我希望这种模式的用户能够简单地从InitCRTP<WantInit>
继承而不用担心其他任何事情。如果有帮助,使用C++11
不是问题。
答案 0 :(得分:9)
您可以将变量作为参考模板参数传递。然后需要导致实例化的对象
template <typename T, T /*unnamed*/>
struct NonTypeParameter { };
template <typename T>
class InitCRTP
{
public:
static InitHelper init;
typedef NonTypeParameter<InitHelper&, init> object_user_dummy;
};