std::tuple_size
來自 cppreference.com
定義於標頭檔案 <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 (函式模板) |