std::is_base_of
來自 cppreference.com
定義於標頭檔案 <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) |
指定型別派生自另一型別 (概念) |