命名空间
变体
操作

std::is_base_of

来自 cppreference.cn
< cpp‎ | types
 
 
元编程库
类型特征
类型类别
(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
[静态]
如果 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 即使 AB 的私有、保护或歧义基类,也为 true。在许多情况下,std::is_convertible<B*, A*> 是更合适的测试。

虽然没有类是其自身的基类,但 std::is_base_of<T, T>::value 为 true,因为该特征的目的是模拟 “is-a” 关系,而 T 是一个 T。尽管如此,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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 2015 C++11 如果行为可能是未定义的
Derived 是一个不完整的联合类型
在这种情况下,基本特征是
std::false_type

[编辑] 参见

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