使用CRTP强制显式模板实例化

时间:2014-07-13 17:05:34

标签: c++ templates c++11 crtp

我正在尝试使用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不是问题。

1 个答案:

答案 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;
};