c++ - 仅为派生类启用模板化基类
问题描述
我将如何去做相当于以下的事情?
template < class T, typename = std::enable_if< std::is_base_of< Self, T >::value > > // Can not use std::is_base_of on self
class Self {
protected:
typedef T self;
};
class ValidDerived : public Self< ValidDerived > { }; // This should compile because T is itself
class InvalidDerived : public Self< ValidDerived > { }; // This should not compile because T is not itself
我正在尝试实现反射,并且要做到这一点,我必须做的其中一个步骤是获取typeid( self ).name()
最派生类。
解决方案
在 CRTP 中,T
在class MyClass : Self<MyClass> {};
.
您可以在应该调用/实例化的方法中添加额外的检查(例如构造函数/析构函数):
template<class T>
class Self
{
protected:
using self = T;
Self() { static_assert(std::is_base_of<Self, T >::value); }
};
推荐阅读
- java - 字符串操作 - 将第二个单词的字符删除到第一个单词
- symfony - 如何在 symfony 应用程序中为纤细的前端设置多个入口点?
- java - SQL Server:使用 Java 8 使用 NTLM 身份验证连接到数据库
- javascript - 将 Preact 渲染并封装到 iframe 中
- java - java.lang.IllegalArgumentException:不是托管类型 - Spring Boot 中的多个数据库
- azure - 使用访问限制将应用程序网关 (WAFv2) 前端 IP 列入白名单会导致应用服务出现 403
- c - 对 C 整数常量表达式使用强制转换或宏
- javascript - 在 React.js 组件中添加 props 作为 HTML 属性
- python - 什么是毫秒指令?像 %f 是微秒
- vue.js - FabricJS v3.4.0:过滤器和 maxTextureSize - 性能/尺寸限制