std::is_base_of
来自 cppreference.cn
                    
                                        
                    
                    
                                                            
                    | 定义于头文件  <type_traits> | ||
| template< class Base, class Derived > struct is_base_of; | (C++11 起) | |
std::is_base_of 是一个 二元类型特征 (BinaryTypeTrait)。
如果 Derived 派生自 Base,或者两者是相同的非联合类(两种情况都忽略 cv 限定),则提供成员常量 value 等于 true。否则 value 为 false。
如果 Base 和 Derived 都是非联合类类型,并且它们不是相同的类型(忽略 cv 限定),则 Derived 应该是一个完整类型;否则行为未定义。
如果程序为 std::is_base_of 或 std::is_base_of_v(C++17 起) 添加特化,则行为未定义。
| 目录 | 
[编辑] 辅助变量模板
| template< class Base, class Derived > constexpr bool is_base_of_v = is_base_of<Base, Derived>::value; | (C++17 起) | |
继承自 std::integral_constant
成员常量
| value [静态] | true 如果 Derived派生自Base或者两者是相同的非联合类(两种情况都忽略 cv 限定),否则为 false(public static 成员常量) | 
成员函数
| operator bool | 将对象转换为 bool,返回 value (公开成员函数) | 
| operator() (C++14) | 返回 value (公开成员函数) | 
成员类型
| 类型 | 定义 | 
| value_type | bool | 
| 类型 | std::integral_constant<bool, value> | 
[编辑] 注意
std::is_base_of<A, B>::value 为 true,即使 A 是 B 的私有、保护或模糊基类。在许多情况下,std::is_convertible<B*, A*> 是更合适的测试。
尽管任何类都不是它自己的基类,std::is_base_of<T, T>::value 为 true,因为该特征的意图是建模“是-一个”关系,并且 T 是 T。尽管如此,std::is_base_of<int, int>::value 为 false,因为只有类才参与该特征所建模的关系。
[编辑] 可能的实现
| namespace details { template<typename B> std::true_type test_ptr_conv(const volatile B*); template<typename> std::false_type test_ptr_conv(const volatile void*); template<typename B, typename D> auto test_is_base_of(int) -> decltype(test_ptr_conv<B>(static_cast<D*>(nullptr))); template<typename, typename> auto test_is_base_of(...) -> std::true_type; // private or ambiguous base } template<typename Base, typename Derived> struct is_base_of : std::integral_constant< bool, std::is_class<Base>::value && std::is_class<Derived>::value && decltype(details::test_is_base_of<Base, Derived>(0))::value > {}; | 
[编辑] 示例
运行此代码
#include <type_traits> class A {}; class B : A {}; class C : B {}; class D {}; union E {}; using I = int; static_assert ( std::is_base_of_v<A, A> == true && std::is_base_of_v<A, B> == true && std::is_base_of_v<A, C> == true && std::is_base_of_v<A, D> != true && std::is_base_of_v<B, A> != true && std::is_base_of_v<E, E> != true && std::is_base_of_v<I, I> != true ); int main() {}
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 | 
|---|---|---|---|
| LWG 2015 | C++11 | 行为可能未定义,如果 Derived是一个不完整的联合类型 | 基特征是 在这种情况下为 std::false_type | 
[编辑] 参见
| (C++26) | 检查一个类型是否为另一个类型的虚基类 (类模板) | 
| (C++11)(C++20) | 检查一个类型是否可以转换为另一个类型 (类模板) | 
| (C++20) | 指定类型派生自另一类型 (概念) | 


