首页 > 解决方案 > 使用 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吗?

标签: c++templatesinheritancesfinae

解决方案


你可能会做

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*>()));

演示


推荐阅读