std:: tuple_size
|
定义于头文件
<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 中弃用) |
提供对 类元组 类型中元素数量的访问,以编译时常量表达式的形式呈现。
|
(2-4)
是 SFINAE 友好的:若将
std
::
tuple_size
<
T
>
::
value
作为未求值操作数处理时其格式错误,则它们不提供成员
value
。访问检查的执行环境与
#include <utility> struct X { int a, b; }; const auto [x, y] = X(); // 结构化绑定声明首先尝试 // tuple_size<const X>,该操作尝试使用 tuple_size<X>::value, // 随后遇到软错误,转而绑定到公共数据成员 |
(since C++17) |
目录 |
特化
标准库为以下标准库类型提供了特化版本:
|
(C++11)
|
获取
|
|
(C++11)
|
获取
pair
的大小
(类模板特化) |
|
(C++11)
|
获取
array
的大小
(类模板特化) |
|
获取
std::ranges::subrange
的大小
(类模板特化) |
|
|
(C++26)
|
获取
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
[static]
|
对于标准特化,表示元组式类型
T
中的元素数量
(公开静态成员常量) |
成员函数
|
operator std::size_t
|
将对象转换为
std::
size_t
,返回
value
(公开成员函数) |
|
operator()
(C++14)
|
返回
value
(公开成员函数) |
成员类型
| 类型 | 定义 |
value_type
|
std:: size_t |
type
|
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]; }; // 程序定义的 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>); // 使用 using 模板 (C++17) using array3x4 = std::array<std::array<int, 3>, 4>; static_assert(4 == std::tuple_size<array3x4>{}); // 使用 operator std::size_t using pair = std::pair<tuple1, array3x4>; static_assert(2 == std::tuple_size<pair>()); // 使用 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
(函数模板) |