std::is_aggregate
来自 cppreference.cn
| 定义于头文件 <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 是数组类型,行为即已定义。 |