std::integer_sequence
提供: cppreference.com
ヘッダ <utility> で定義
|
||
template< class T, T... Ints > class integer_sequence; |
(C++14以上) | |
クラステンプレート std::integer_sequence
はコンパイル時整数列を表します。 関数テンプレートの引数として使用すると、パラメータパック Ints
を推定でき、パック展開で使用できます。
目次 |
[編集] テンプレート引数
T | - | 整数列の要素のために使用する整数型 |
...Ints | - | 整数列を表す非型パラメータパック |
[編集] メンバ型
メンバ型 | 定義 |
value_type
|
T
|
[編集] メンバ関数
size [静的] |
Ints の要素数を返します (パブリック静的メンバ関数) |
std::integer_sequence::size
static constexpr std::size_t size() noexcept; |
||
Ints
の要素の数を返します。 sizeof...(Ints) と同等です。
引数
(なし)
戻り値
Ints
の要素の数。
[編集] ヘルパーテンプレート
T
が std::size_t である一般的なケースのためにヘルパーエイリアステンプレート std::index_sequence
が定義されます。
template<std::size_t... Ints> using index_sequence = std::integer_sequence<std::size_t, Ints...>; |
||
Ints
として 0, 1, 2, ..., N-1
を持つ std::integer_sequence
および std::index_sequence
の作成を簡単にするためにヘルパーエイリアステンプレート std::make_integer_sequence
が定義されます。
template<class T, T N> using make_integer_sequence = std::integer_sequence<T, /* a sequence 0, 1, 2, ..., N-1 */ >; |
||
template<std::size_t N> using make_index_sequence = make_integer_sequence<std::size_t, N>; |
||
N
が負の場合、プログラムは ill-formed です。 N
がゼロの場合、示される型は integer_sequence<T>
になります。
任意の型のパラメータパックを同じ長さの整数列に変換するためにヘルパーエイリアステンプレート std::index_sequence_for
が定義されます。
template<class... T> using index_sequence_for = std::make_index_sequence<sizeof...(T)>; |
||
[編集] 例
ノート: std::apply の実装例にある別の例も参照してください。
Run this code
#include <tuple> #include <iostream> #include <array> #include <utility> // Convert array into a tuple template<typename Array, std::size_t... I> auto a2t_impl(const Array& a, std::index_sequence<I...>) { return std::make_tuple(a[I]...); } template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>> auto a2t(const std::array<T, N>& a) { return a2t_impl(a, Indices{}); } // pretty-print a tuple template<class Ch, class Tr, class Tuple, std::size_t... Is> void print_tuple_impl(std::basic_ostream<Ch,Tr>& os, const Tuple& t, std::index_sequence<Is...>) { ((os << (Is == 0? "" : ", ") << std::get<Is>(t)), ...); } template<class Ch, class Tr, class... Args> auto& operator<<(std::basic_ostream<Ch, Tr>& os, const std::tuple<Args...>& t) { os << "("; print_tuple_impl(os, t, std::index_sequence_for<Args...>{}); return os << ")"; } int main() { std::array<int, 4> array = {1,2,3,4}; // convert an array into a tuple auto tuple = a2t(array); static_assert(std::is_same<decltype(tuple), std::tuple<int, int, int, int>>::value, ""); // print it to cout std::cout << tuple << '\n'; }
出力:
(1, 2, 3, 4)