名稱空間
變體
操作

std::is_polymorphic

來自 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)
is_polymorphic
(C++11)
(C++14)
(C++11)(C++26 中已棄用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已棄用)
(C++11)
型別特性常量
元函式
(C++17)
支援的操作
關係與屬性查詢
型別修改
(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 T >
struct is_polymorphic;
(C++11 起)

std::is_polymorphic 是一個 UnaryTypeTrait

T多型類(即宣告或繼承至少一個虛擬函式的非聯合類),則提供等於 true 的成員常量 value。對於任何其他型別,valuefalse

T 是不完整非聯合類型別,則行為未定義。

若程式新增 std::is_polymorphicstd::is_polymorphic_v 的特化,則行為未定義。

目錄

[編輯] 模板引數

T - 要檢查的型別

[編輯] 幫助變數模板

template< class T >
constexpr bool is_polymorphic_v = is_polymorphic<T>::value;
(C++17 起)

繼承自 std::integral_constant

成員常量

value
[靜態]
T多型類型別則為 true,否則為 false
(public static 成員常量)

成員函式

operator bool
將物件轉換為 bool,返回 value
(公開成員函式)
operator()
(C++14)
返回 value
(公開成員函式)

成員型別

型別 定義
value_type bool
型別 std::integral_constant<bool, value>

[編輯] 可能的實現

namespace detail
{
    template<class T>
    std::true_type detect_is_polymorphic(
        decltype(dynamic_cast<const volatile void*>(static_cast<T*>(nullptr)))
    );
    template<class T>
    std::false_type detect_is_polymorphic(...);
} // namespace detail
 
template<class T>
struct is_polymorphic : decltype(detail::detect_is_polymorphic<T>(nullptr)) {};

[編輯] 示例

#include <type_traits>
 
struct A { int m; };
static_assert(!std::is_polymorphic_v<A>);
 
struct B { virtual void foo(); };
static_assert(std::is_polymorphic_v<B>);
 
struct C : B {};
static_assert(std::is_polymorphic_v<C>);
 
struct D { virtual ~D() = default; };
static_assert(std::is_polymorphic_v<D>);
 
// Uses inheritance, but not the virtual keyword:
struct E : A {};
static_assert(!std::is_polymorphic_v<E>);
 
struct F : virtual A {};
static_assert(!std::is_polymorphic_v<F>);
 
struct AX : A {};
struct AY : A {};
struct XY : virtual AX, virtual AY {};
static_assert(!std::is_polymorphic_v<XY>);
 
int main() {}

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2015 C++11
T 是不完整聯合型別
基特徵是
在這種情況下為 std::false_type

[編輯] 參閱

(C++11)
檢查型別是否為非聯合類型別
(類模板) [編輯]
檢查型別是否為抽象類型別
(類模板) [編輯]
檢查型別是否具有虛解構函式
(類模板) [編輯]