命名空间
变体
操作

std::is_aggregate

来自 cppreference.cn
< cpp‎ | types
 
 
元编程库
类型特征
类型类别
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
类型属性
(C++11)
(C++11)
(C++14)
is_aggregate
(C++17)
(C++11)(在 C++26 中弃用)
(C++11)(直到 C++20*)
(C++11)(在 C++20 中弃用)
(C++11)
类型特征常量
元函数
(C++17)
(C++17)
(C++17)
支持的操作
关系与属性查询
类型修改
(C++11)(C++11)(C++11)
类型转换
(C++11)(在 C++23 中弃用)
(C++11)(在 C++23 中弃用)
(C++11)
(C++11)(直到 C++20*)(C++17)

(C++11)
(C++17)
编译时有理算术
编译时整数序列
 
定义于头文件 <type_traits>
template< class T >
struct is_aggregate;
(自 C++17 起)

std::is_aggregate 是一个 一元类型特征 (UnaryTypeTrait)

如果 T 是一个 聚合类型,则提供等于 true 的成员常量 value 。对于任何其他类型,valuefalse

如果 T 是一个不完整类型,且不是数组类型或(可能带 cv 限定的)void,则行为未定义。

如果程序为 std::is_aggregatestd::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 是数组类型。