名稱空間
變體
操作

std::is_base_of

來自 cppreference.com
< 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

[編輯] 參見

檢查一個型別是否為另一個型別的虛基類
(類模板) [編輯]
檢查一個型別是否可以轉換為另一個型別
(類模板) [編輯]
指定型別派生自另一型別
(概念) [編輯]