使用CRTP强制显式模板实例化 [英] Force explicit template instantiation with CRTP
问题描述
我试图使用一个CRTPed基地持有一些静态初始化代码,如下:
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;
现在,任何需要在 InitHelper< T&
可以这样做:
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>`.
强制实例化 InitCRTP< WantInit> :: init
,我可以使用 dummy
或使用显式实例化如上所示。有没有办法解决这个问题?我想让这种模式的用户能够简单地继承 InitCRTP< WantInit>
,而不担心任何其他。如果有帮助,使用 C ++ 11
不是问题。
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.
推荐答案
p>您可以将变量作为参考模板参数传递。然后需要导致实例化的对象
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;
};
这篇关于使用CRTP强制显式模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!