命名空间
变体
操作

std::is_base_of

来自 cppreference.cn
< cpp‎ | 类型
 
 
元编程库
类型特性
类型类别
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
类型属性
(C++11)
(C++11)
(C++14)
(C++11)(C++26 中已弃用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已弃用)
(C++11)
类型特性常量
元函数
(C++17)
支持的操作
关系与属性查询
is_base_of
(C++11)
(C++11)
(C++11)
类型修改
(C++11)(C++11)(C++11)
类型转换
(C++11)(C++23 中已弃用)
(C++11)(C++23 中已弃用)
(C++11)
(C++11)(直到 C++20*)(C++17)

(C++11)
(C++17)
编译时有理数算术
编译时整数序列
 
定义于头文件 <type_traits>
template< class Base, class Derived >
struct is_base_of;
(C++11 起)

std::is_base_of 是一个 二元类型特征 (BinaryTypeTrait)

如果 Derived 派生自 Base,或者两者是相同的非联合类(两种情况都忽略 cv 限定),则提供成员常量 value 等于 true。否则 valuefalse

如果 BaseDerived 都是非联合类类型,并且它们不是相同的类型(忽略 cv 限定),则 Derived 应该是一个完整类型;否则行为未定义。

如果程序为 std::is_base_ofstd::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>::valuetrue,即使 AB 的私有、保护或模糊基类。在许多情况下,std::is_convertible<B*, A*> 是更合适的测试。

尽管任何类都不是它自己的基类,std::is_base_of<T, T>::value 为 true,因为该特征的意图是建模“是-一个”关系,并且 TT。尽管如此,std::is_base_of<int, int>::valuefalse,因为只有类才参与该特征所建模的关系。

[编辑] 可能的实现

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

[编辑] 参见

检查一个类型是否为另一个类型的虚基类
(类模板) [编辑]
检查一个类型是否可以转换为另一个类型
(类模板) [编辑]
指定类型派生自另一类型
(概念) [编辑]