std::is_empty
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class T > struct is_empty; |
(C++11 起) | |
std::is_empty
是一個 一元型別特性。
若 T
為空型別(即,除大小為 0 的位域之外無非靜態資料成員,無虛擬函式,無虛基類,且無非空基類的非聯合類型別),則提供等於 true 的成員常量 value
。對於任何其他型別,value
為 false。
若 T
是不完整非聯合類型別,則行為未定義。
如果程式為 std::is_empty
或 std::is_empty_v
新增特化,則行為未定義。
目錄 |
[編輯] 模板引數
T | - | 要檢查的型別 |
[編輯] 輔助變數模板
template< class T > constexpr bool is_empty_v = is_empty<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> |
[編輯] 注意
由於空基類最佳化,從空基類繼承通常不會增加類的大小。
std::is_empty<T>
和所有其他型別特性都是空類。
[編輯] 示例
執行此程式碼
#include <iostream> #include <type_traits> struct A {}; static_assert(std::is_empty_v<A> == true); struct B { int m; }; static_assert(std::is_empty_v<B> == false); struct C { static int m; }; static_assert(std::is_empty_v<C> == true); struct D { virtual ~D(); }; static_assert(std::is_empty_v<D> == false); union E {}; static_assert(std::is_empty_v<E> == false); struct F { [[no_unique_address]] E e; }; struct G { int:0; // C++ standard allow "as a special case, an unnamed bit-field with a width of zero // specifies alignment of the next bit-field at an allocation unit boundary. // Only when declaring an unnamed bit-field may the width be zero." }; static_assert(std::is_empty_v<G>); // holds only unnamed bit-fields of zero width int main() { std::cout << std::boolalpha; std::cout << "F: " << std::is_empty_v<F> << '\n'; // the result is ABI-dependent }
可能的輸出
F: true
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2015 | C++11 | 若T 是不完整聯合型別 |
基特徵是 在這種情況下為 std::false_type |
[編輯] 參閱
(C++11) |
檢查型別是否為非聯合類型別 (類模板) |