Namespaces
Variants

std:: is_aggregate

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
is_aggregate
(C++17)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <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 添加特化,则行为是未定义的。

目录

模板参数

T - 待检查的类型

辅助变量模板

template < class T >
constexpr bool is_aggregate_v = is_aggregate < T > :: value ;
(自 C++17 起)

继承自 std:: integral_constant

成员常量

value
[static]
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> 是否完整
其行为均有定义