-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprint_tuple1.cpp
41 lines (35 loc) · 1000 Bytes
/
print_tuple1.cpp
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
// print_tuple1.cpp : output a tuple using class and member function templates with TMP
// note: compile with -std=c++17 or later
#include <iostream>
#include <tuple>
using namespace std;
template<size_t N>
struct TupleOstream {
template<typename... Args>
static void print(ostream& os, const tuple<Args...>&t) {
os << get<sizeof...(Args) - N - 1>(t) << ", ";
TupleOstream<N - 1>::print(os, t);
}
};
template<>
struct TupleOstream<0> {
template<typename... Args>
static void print(ostream& os, const tuple<Args...>&t) {
os << get<sizeof...(Args) - 1>(t);
}
};
template<typename... Args>
ostream& operator<<(ostream& os, const tuple<Args...>& t) {
if constexpr (sizeof...(Args) == 0) {
return os << "{}";
}
else {
os << "{ ";
TupleOstream<sizeof...(Args) - 1>::print(os, t);
return os << " }";
}
}
int main() {
tuple my_tuple{ "Hi", 2, 0xALL, 0U, "folks!" };
cout << my_tuple << '\n';
}