std::tuple_size
来自 cppreference.cn
定义于头文件 <array> |
||
定义于头文件 <tuple> |
||
在头文件 <utility> 中定义 |
||
定义于头文件 <ranges> |
(C++20 起) |
|
定义于头文件 <complex> |
(C++26 起) |
|
template< class T > struct tuple_size; // 未定义 |
(1) | (C++11 起) |
template< class T > struct tuple_size< const T > |
(2) | (C++11 起) |
template< class T > struct tuple_size< volatile T > |
(3) | (C++11 起) (C++20 中已弃用) |
template< class T > struct tuple_size< const volatile T > |
(4) | (C++11 起) (C++20 中已弃用) |
在编译时以常量表达式的形式提供对类元组(tuple-like)类型中元素数量的访问。
1) 主模板未定义。需要显式(完整)或部分特化以使类型成为类元组。
2-4) cv 限定类型的特化默认重用对应 cv 非限定版本的 value。
(2-4) 是 SFINAE 友好的:如果 std::tuple_size<T>::value 在被视为未求值操作数时格式错误,它们将不提供成员 value。访问检查的执行方式如同在与 #include <utility> struct X { int a, b; }; const auto [x, y] = X(); // structured binding declaration first attempts // tuple_size<const X> which attempts to use tuple_size<X>::value, // then soft error encountered, binds to public data members |
(C++17 起) |
目录 |
[编辑] 特化
标准库为标准库类型提供以下特化
(C++11) |
获取 tuple 的大小一个 |
(C++11) |
获取 pair 的大小(类模板特化) |
(C++11) |
获得 array 的大小(类模板特化) |
获取 std::ranges::subrange 的大小 (类模板特化) | |
获取 std::complex 的大小 (类模板特化) |
所有 std::tuple_size
的特化都满足 一元类型特性 (UnaryTypeTrait),其基本特性为 std::integral_constant<std::size_t, N>,其中 N
为某个值。
用户可以为程序定义类型特化 std::tuple_size
以使它们成为类元组。程序定义的特化必须满足上述要求。
通常只需要为 cv 非限定类型定制特化。
[编辑] 辅助变量模板
定义于头文件 <tuple> |
||
template< class T > constexpr std::size_t tuple_size_v = tuple_size<T>::value; |
(C++17 起) | |
继承自 std::integral_constant
成员常量
value [静态] |
对于标准特化,类元组类型 T 中的元素数量(public static 成员常量) |
成员函数
operator std::size_t |
将对象转换为 std::size_t,返回 value (公开成员函数) |
operator() (C++14) |
返回 value (公开成员函数) |
成员类型
类型 | 定义 |
value_type
|
std::size_t |
类型
|
std::integral_constant<std::size_t, value> |
[编辑] 示例
运行此代码
#include <array> #include <cstddef> #include <ranges> #include <tuple> #include <utility> template<class T, std::size_t Size> struct Arr { T data[Size]; }; // Program-defined specialization of std::tuple_size: template<class T, std::size_t Size> struct std::tuple_size<Arr<T, Size>> : public integral_constant<std::size_t, Size> {}; int main() { using tuple1 = std::tuple<int, char, double>; static_assert(3 == std::tuple_size_v<tuple1>); // uses using template (C++17) using array3x4 = std::array<std::array<int, 3>, 4>; static_assert(4 == std::tuple_size<array3x4>{}); // uses operator std::size_t using pair = std::pair<tuple1, array3x4>; static_assert(2 == std::tuple_size<pair>()); // uses operator() using sub = std::ranges::subrange<char*, char*>; static_assert(2 == std::tuple_size<sub>::value); using Arr5 = Arr<int, 5>; static_assert(5 == std::tuple_size_v<Arr5>); }
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 2212 | C++11 | 某些头文件中不需要 cv 类型的特化,导致歧义 | 需要 |
[编辑] 参见
结构化绑定 (C++17) | 将指定的名称绑定到初始化器的子对象或元组元素 |
(C++11) |
获取类元组类型的元素类型 (类模板) |
(C++11) |
通过连接任意数量的 tuple 创建一个 tuple (函数模板) |