std::is_aggregate
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T > struct is_aggregate; |
(自 C++17 起) | |
std::is_aggregate
是一个 一元类型特征 (UnaryTypeTrait)。
如果 T
是一个 聚合类型,则提供等于 true 的成员常量 value
。对于任何其他类型,value
为 false。
如果 T
是一个不完整类型,且不是数组类型或(可能带 cv 限定的)void,则行为未定义。
如果程序为 std::is_aggregate
或 std::is_aggregate_v
添加特化,则行为未定义。
内容 |
[edit] 模板形参
T | - | 要检查的类型 |
[edit] 辅助变量模板
template< class T > constexpr bool is_aggregate_v = is_aggregate<T>::value; |
(自 C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] |
true 如果 T 是聚合类型,否则为 false(公共静态成员常量) |
成员函数
operator bool |
将对象转换为 bool,返回 value (公共成员函数) |
operator() (C++14) |
返回 value (公共成员函数) |
成员类型
类型 | 定义 |
value_type
|
bool |
type
|
std::integral_constant<bool, value> |
[edit] 注释
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_is_aggregate |
201703L |
(C++17) | std::is_agregate
|
[edit] 示例
运行此代码
#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"); }
[edit] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 3823 | C++17 | 如果 T 是数组类型但std::remove_all_extents_t<T> 是不完整类型,则行为未定义。 |
无论 std::remove_all_extents_t<T> 的不完整性如何,行为都是已定义的 只要 T 是数组类型。 |