Force explicit template instantiation with CRTP

纵然是瞬间 提交于 2019-11-27 03:41:41

问题


I am trying to use a CRTPed base to hold some static initialization code like this:

template <typename T>
class InitCRTP
{
public:
static InitHelper<T> init;
};

template <typename T> InitHelper<T> InitCRTP<T>::init;

Now, any class which needs to do the work in InitHelper<T> can do this:

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>`.

To force instantiation of InitCRTP<WantInit>::init, I can either use dummy or use the explicit instantiation as shown above. Is there a way of getting around this with doing neither? I would like users of this pattern to be able to simply inherit from InitCRTP<WantInit> and not worry about anything else. If it helps, using C++11 is not an issue.


回答1:


You could pass the variable as a reference template argument. Then the object is needed which causes an instantiation

template <typename T, T /*unnamed*/>
struct NonTypeParameter { };

template <typename T>
class InitCRTP
{
public:
     static InitHelper init;
     typedef NonTypeParameter<InitHelper&, init> object_user_dummy;
};


来源:https://stackoverflow.com/questions/24725152/force-explicit-template-instantiation-with-crtp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!