-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteger_sequence.cpp
More file actions
60 lines (51 loc) · 1.79 KB
/
integer_sequence.cpp
File metadata and controls
60 lines (51 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#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);
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';
}