C++17中如何判断一个类型是否直接派生自另一个类型
1级直接继承判断实现方案(C++17 MSVC兼容)
完整实现代码
#include <type_traits> template <typename Base, typename Derived> struct Is1LevelSubClass { private: // 辅助类继承目标派生类 struct Helper : Derived { // 匹配直接基类转换场景 template <typename T> static constexpr std::true_type test(T*); // 匹配间接基类/非基类场景 static constexpr std::false_type test(void*); }; public: static constexpr bool value = // 首先过滤非基类、同类型的情况 std::is_base_of_v<Base, Derived> && !std::is_same_v<Base, Derived> // 判断是否为直接基类 && std::is_same_v<decltype(Helper::test(static_cast<Helper*>(nullptr))), std::true_type>; }; // 便捷变量模板,符合C++标准库使用习惯 template <typename Base, typename Derived> constexpr bool Is1LevelSubClass_v = Is1LevelSubClass<Base, Derived>::value;
测试验证
针对你给出的示例可以直接通过静态断言验证效果:
class A {}; class B : public A {}; class C : public B {}; // 结果完全符合需求 static_assert(Is1LevelSubClass<A, C>::value == false); static_assert(Is1LevelSubClass<B, C>::value == true); static_assert(std::is_base_of_v<A, C> == true); static_assert(std::is_base_of_v<B, C> == true);
注意事项
- 仅支持公开继承场景,私有、保护继承无法正确判断
- 单继承场景下完全匹配需求,多继承场景可基于此逻辑调整实现
- 兼容MSVC 2017及以上所有支持C++17标准的编译器版本
内容的提问来源于stack exchange,提问作者SungJin Kang
相关产品推荐
相关产品推荐

