使用CRTP强制显式模板实例化
Force explicit template instantiation with 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
不是问题。
您可以将该变量作为引用模板参数传递。然后需要对象,导致实例化
template <typename T, T /*unnamed*/>
struct NonTypeParameter { };
template <typename T>
class InitCRTP
{
public:
static InitHelper init;
typedef NonTypeParameter<InitHelper&, init> object_user_dummy;
};
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- CRTP 模式不会触发完整的模板实例化
- 延迟 crtp 基类中的成员函数实例化
- C++CRTP虚拟函数的实例化点
- 使用CRTP强制显式模板实例化