Namespaces
Variants

std:: is_base_of

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <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
[static]
Derived 派生自 Base 或两者为同一非联合类(两种情况均忽略 cv 限定符)则为 true ,否则为 false
(公开静态成员常量)

成员函数

operator bool
转换对象为 bool 类型,返回 value
(公开成员函数)
operator()
(C++14)
返回 value
(公开成员函数)

成员类型

类型 定义
value_type bool
type 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 的值仍为真,因为该特性的设计意图是模拟“是一个”的关系,而 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; // 私有或模糊基类
}
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

参见

检查一个类型是否是另一个类型的虚基类
(类模板)
检查一个类型是否能转换为另一个类型
(类模板)
指定一个类型派生自另一个类型
(概念)