C++ tuple输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// c++11
template<typename Tuple, size_t N>
struct tuple_print {
static void print(const Tuple& t, std::ostream& os) {
tuple_print<Tuple, N - 1>::print(t, os);
os << ", " << std::get<N - 1>(t);
}
};
// 类模板的特化版本
template<typename Tuple>
struct tuple_print<Tuple, 1> {
static void print(const Tuple& t, std::ostream& os) {
os << "(" << std::get<0>(t);
}
};

// operator<<
template<typename... Args>
std::ostream& operator <<(std::ostream& os, const std::tuple<Args...>& t) {
tuple_print<decltype(t), sizeof...(Args)>::print(t, os);
return os << ")";
}
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
//C++14
// 数组转换为 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{});
}

// 漂亮地打印 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 << ")";
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2020-2021 一潭清泓
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信