std::integer_sequence
Определён в заголовке <utility> | ||
|---|---|---|
template< class T, T... Ints > struct integer_sequence; | (начиная с C++14) |
Шаблон класса std::integer_sequence представляет собой последовательность целых чисел, создаваемую во время компиляции. При использовании в качестве аргумента шаблона функции пакет параметров Ints может быть выведен и использован при раскрытии пакета.
Параметры шаблона
| T | - | целочисленный тип для элементов последовательности |
| ...Ints | - | пакет нетиповых параметров, представляющий последовательность |
Типы-члены
| Тип | Определение |
|---|---|
value_type |
T |
Функции-члены
|
[статическая] | возвращает количество элементов в 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...>; |
Вспомогательные шаблоны псевдонимов std::make_integer_sequence и std::make_index_sequence определены для упрощения создания типов std::integer_sequence и std::index_sequence соответственно, где 0, 1, 2, ..., N - 1 являются Ints:
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 = std::make_integer_sequence<std::size_t, N>; |
Программа некорректна, если N отрицательно. Если N равно нулю, указанный тип является integer_sequence<T>.
Вспомогательный шаблон псевдонима std::index_sequence_for определён для преобразования любого пакета параметров типов в последовательность индексов той же длины:
template< class... T > using index_sequence_for = std::make_index_sequence<sizeof...(T)>; |
Примечания
| Макрос проверки наличия функции | Значение | Стандарт | Функция |
|---|---|---|---|
__cpp_lib_integer_sequence | 201304L | (C++14) | Целочисленные последовательности, создаваемые во время компиляции |
Возможная реализация
| make_integer_sequence |
|---|
namespace detail {
template<class T, T I, T N, T... integers>
struct make_integer_sequence_helper
{
using type = typename make_integer_sequence_helper<T, I + 1, N, integers..., I>::type;
};
template<class T, T N, T... integers>
struct make_integer_sequence_helper<T, N, N, integers...>
{
using type = std::integer_sequence<T, integers...>;
};
}
template<class T, T N>
using make_integer_sequence = typename detail::make_integer_sequence_helper<T, 0, N>::type;
|
Пример
Другой пример см. также в возможной реализации std::apply.
#include <array>
#include <cstddef>
#include <iostream>
#include <tuple>
#include <utility>
namespace details {
template <typename Array, std::size_t... I>
constexpr auto array_to_tuple_impl(const Array& a, std::index_sequence<I...>)
{
return std::make_tuple(a[I]...);
}
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 ? ", " : "") << std::get<Is>(t)), ...);
}
}
template <typename T, T... ints>
void print_sequence(int id, std::integer_sequence<T, ints...> int_seq)
{
std::cout << id << ") The sequence of size " << int_seq.size() << ": ";
((std::cout << ints << ' '), ...);
std::cout << '\n';
}
template <typename T, std::size_t N, typename Indx = std::make_index_sequence<N>>
constexpr auto array_to_tuple(const std::array<T, N>& a)
{
return details::array_to_tuple_impl(a, Indx{});
}
template <class Ch, class Tr, class... Args>
auto& operator<<(std::basic_ostream<Ch, Tr>& os, const std::tuple<Args...>& t)
{
os << '(';
details::print_tuple_impl(os, t, std::index_sequence_for<Args...>{});
return os << ')';
}
int main()
{
print_sequence(1, std::integer_sequence<unsigned, 9, 2, 5, 1, 9, 1, 6>{});
print_sequence(2, std::make_integer_sequence<int, 12>{});
print_sequence(3, std::make_index_sequence<10>{});
print_sequence(4, std::index_sequence_for<std::ios, float, signed>{});
constexpr std::array<int, 4> array{1, 2, 3, 4};
auto tuple1 = array_to_tuple(array);
static_assert(std::is_same_v<decltype(tuple1),
std::tuple<int, int, int, int>>, "");
std::cout << "5) tuple1: " << tuple1 << '\n';
constexpr auto tuple2 = array_to_tuple<int, 4,
std::integer_sequence<std::size_t, 1, 0, 3, 2>>(array);
std::cout << "6) tuple2: " << tuple2 << '\n';
}
Вывод:
1) The sequence of size 7: 9 2 5 1 9 1 6 2) The sequence of size 12: 0 1 2 3 4 5 6 7 8 9 10 11 3) The sequence of size 10: 0 1 2 3 4 5 6 7 8 9 4) The sequence of size 3: 0 1 2 5) tuple1: (1, 2, 3, 4) 6) tuple2: (2, 1, 4, 3)
См. также
|
(C++20) | создаёт объект std::array из встроенного массива (шаблон функции) |
|
(C++11)(C++17) | константа времени компиляции указанного типа и значения (шаблон класса) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/utility/integer_sequence