c++ - 使用 SFINAE 在 C++ 中检查模板父类
问题描述
我最近一直在学习 C++ 中 SFINAE 的概念,我目前正在尝试在项目中使用它。
问题是,我正在尝试做的事情与我能找到的任何事情都不同,而且我不知道该怎么做。
假设我有一个名为 MyParent 的模板类:
template <typename Elem>
class MyParent;
还有一个名为 MyClass 的非模板类,它继承了它,使用 char 作为 Elem:
class MyClass : public MyParent<char>;
现在,我想使用 SFINAE 来检查类型名是否继承MyParent
,无论使用什么Elem
类型。
std::is_base_of
由于父母的模板,我不能使用。
我尝试执行以下操作:
template <typename T>
struct is_my_parent : std::false_type {};
template <typename Elem>
struct is_my_parent<MyParent<Elem>> : std::true_type {};
现在,如果我检查is_my_parent<MyParent<Elem>>::value
,它会给我true
. 哪个好。但是,当我检查 时is_my_parent<MyClass>::value
,我会收到false
. 哪种有意义,因为MyClass
实际上不是MyParent<Elem>
,但我没有设法得到我想要的。
is_my_parent
除了为继承自的每个类定义之外,还有什么方便的方法可以在 C++ 中实现这样的目标MyParent
吗?
解决方案
你可能会做
template <typename T>
std::true_type is_my_parent_impl(const MyParent<T>*);
std::false_type is_my_parent_impl(const void*);
template <typename T>
using is_my_parent = decltype(is_my_parent_impl(std::declval<T*>()));
推荐阅读
- javascript - 我想要一个源代码来学习如何在我的 React Native 应用程序中使用 Redux 创建用户组?
- material-design-in-xaml - 继承的控件不继承 Material Design 风格
- angular - 在其他组件Angular中使用组件方法
- python - 显示 jinja 中字典列表中的所有值
- r - 用于计算张量积的 R 向量内存已耗尽
- node.js - 如何使用 Fetch() 和 Node.js 评估来自服务器的 API 响应并在客户端采取相应的行动
- nginx - 用于服务的 Cronjob
- python - 我可以在这里信任用户输入吗?
- javascript - 在自己的域上显示远程网站内容的正确方法
- python - 最低平台