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

Force explicit template instantiation with CRTP

本文关键字:实例化 CRTP 使用      更新时间:2023-10-16

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

您可以将该变量作为引用模板参数传递。然后需要对象,导致实例化

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