std::is_polymorphic
來自 cppreference.com
| 定義於標頭檔案 <type_traits> |
||
| template< class T > struct is_polymorphic; |
(C++11 起) | |
std::is_polymorphic 是一個 UnaryTypeTrait。
若 T 是多型類(即宣告或繼承至少一個虛擬函式的非聯合類),則提供等於 true 的成員常量 value。對於任何其他型別,value 為 false。
若 T 是不完整非聯合類型別,則行為未定義。
若程式新增 std::is_polymorphic 或 std::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) |
檢查型別是否為非聯合類型別 (類模板) |
| (C++11) |
檢查型別是否為抽象類型別 (類模板) |
| (C++11) |
檢查型別是否具有虛解構函式 (類模板) |