Spec-Zone.ru › C++

std::integer_sequence

Определено в заголовке <utility>
template< class T, T... Ints >
class integer_sequence;
(с C++14)

Шаблон класса std::integer_sequence представляет собой последовательность целых чисел во время компиляции. При использовании в качестве аргумента шаблона функции шаблона функции, параметр-упаковку Ints можно вывести и использовать в расширении упаковки.

Параметры шаблона

T - целочисленный тип для использования в качестве элементов последовательности
...Ints - параметр-упаковку нетипового типа, представляющий последовательность

Типы членов

Тип члена Определение
value_type T

Члены-функции

size
[static]
возвращает количество элементов в Ints
(статический член-функция)

std::integer_sequence::size

static constexpr std::size_t size() noexcept;

Возвращает количество элементов в Ints. Эквивалентно sizeof...(Ints).

Параметры

(нет)

Возвращаемое значение

Количество элементов в Ints.

Вспомогательные шаблоны

Вспомогательный шаблон псевдонима std::index_sequence определен для общего случая, когда T является std::size_t:

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) Последовательности целых чисел во время компиляции

Пример

Примечание: см. Возможную реализацию в std::apply для другого примера.

#include <array>
#include <cstddef>
#include <iostream>
#include <tuple>
#include <utility>
 
// debugging aid
template<typename T, T... ints>
void print_sequence(std::integer_sequence<T, ints...> int_seq)
{
    std::cout << "The sequence of size " << int_seq.size() << ": ";
    ((std::cout << ints << ' '), ...);
    std::cout << '\n';
}
 
// 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()
{
    print_sequence(std::integer_sequence<unsigned, 9, 2, 5, 1, 9, 1, 6>{});
    print_sequence(std::make_integer_sequence<int, 20>{});
    print_sequence(std::make_index_sequence<10>{});
    print_sequence(std::index_sequence_for<float, std::iostream, char>{});
 
    std::array<int, 4> array = {1, 2, 3, 4};
 
    // convert an array into a tuple
    auto tuple = a2t(array);
    static_assert(std::is_same_v<decltype(tuple),
                                 std::tuple<int, int, int, int>>, "");
 
    // print it to cout
    std::cout << "The tuple: " << tuple << '\n';
}

Вывод:

The sequence of size 7: 9 2 5 1 9 1 6 
The sequence of size 20: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
The sequence of size 10: 0 1 2 3 4 5 6 7 8 9 
The sequence of size 3: 0 1 2 
The tuple: (1, 2, 3, 4)

См. также

to_array
(C++20)
создаёт объект std::array из встроенного массива
(шаблон функции)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/utility/integer_sequence

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API