std::is_aggregate
來自 cppreference.com
| 定義於標頭檔案 <type_traits> |
||
| template< class T > struct is_aggregate; |
(C++17 起) | |
std::is_aggregate 是一個 一元型別特性 (UnaryTypeTrait)。
若 T 是聚合型別,則提供成員常量 value 等於 true。對於任何其他型別,value 為 false。
若 T 是不完整型別,但不是陣列型別或(可能經 cv 限定的)void,則行為未定義。
若程式為 std::is_aggregate 或 std::is_aggregate_v 新增特化,則行為未定義。
目錄 |
[編輯] 模板引數
| T | - | 要檢查的型別 |
[編輯] 輔助變數模板
| template< class T > constexpr bool is_aggregate_v = is_aggregate<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> |
[編輯] 註解
| 特性測試宏 | 值 | 標準 | 特性 |
|---|---|---|---|
__cpp_lib_is_aggregate |
201703L |
(C++17) | std::is_agregate
|
[編輯] 示例
執行此程式碼
#include <algorithm> #include <cassert> #include <cstddef> #include <new> #include <string_view> #include <type_traits> #include <utility> // Constructs a T at the uninitialized memory pointed to by p using // list-initialization for aggregates and non-list initialization otherwise. template<class T, class... Args> T* construct(T* p, Args&&... args) { if constexpr (std::is_aggregate_v<T>) return ::new (static_cast<void*>(p)) T{std::forward<Args>(args)...}; else return ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...); } struct A { int x, y; }; static_assert(std::is_aggregate_v<A>); struct B { int i; std::string_view str; B(int i, std::string_view str) : i(i), str(str) {} }; static_assert(not std::is_aggregate_v<B>); template <typename... Ts> using aligned_storage_t = alignas(Ts...) std::byte[std::max({sizeof(Ts)...})]; int main() { aligned_storage_t<A, B> storage; A& a = *construct(reinterpret_cast<A*>(&storage), 1, 2); assert(a.x == 1 and a.y == 2); B& b = *construct(reinterpret_cast<B*>(&storage), 3, "4"); assert(b.i == 3 and b.str == "4"); }
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
| 缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
|---|---|---|---|
| LWG 3823 | C++17 | 若 T 是陣列型別但std::remove_all_extents_t<T> 是不完整型別,則行為未定義。 |
無論 std::remove_all_extents_t<T> 的不完整性如何,只要 T 是陣列型別,行為即已定義。 |