std::is_aggregate
来自cppreference.com
<tbody>
</tbody>
| 在标头 <type_traits> 定义
|
||
template< class T > struct is_aggregate; |
(C++17 起) | |
std::is_aggregate 是一元类型特征 (UnaryTypeTrait) 。
如果 T 是聚合类型,那么提供的成员常量 value 等于 true。对于其它任何类型,value 等于 false。
如果 TT 是除数组类型或(可以有 cv 限定的)void 之外的不完整类型,那么行为未定义。
如果程序添加了 std::is_aggregate 或 std::is_aggregate_v 的特化,那么行为未定义。
模板形参
| T | - | 要检查的类型 |
辅助变量模板
<tbody> </tbody> template< class T > constexpr bool is_aggregate_v = is_aggregate<T>::value; |
(C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] |
如果 T 是聚合类型那么是 true,否则是 false (公开静态成员常量) |
成员函数
operator bool |
将对象转换到 bool,返回 value (公开成员函数) |
operator() (C++14) |
返回 value (公开成员函数) |
成员类型
| 类型 | 定义 |
value_type
|
bool
|
type
|
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>
// 于 p 所指向的未初始化内存构造 T
// 对于聚合体使用列表初始化,否则使用非列表初始化
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> 是不完整类型,则行为未定义。
|
只要 T 是数组类型,无论 std::remove_all_extents_t<T>是否完整,都会定义该行为。 |