漂亮打印std :: tuple

这是我先前关于漂亮打印的STL容器的问题的跟进,我们设法为其开发了一个非常优雅且完全通用的解决方案。


在下一步中,我想std::tuple<Args...>使用可变参数模板(严格来说是C ++ 11)包括的漂亮打印。对于std::pair<S,T>,我只是说


std::ostream & operator<<(std::ostream & o, const std::pair<S,T> & p)

{

  return o << "(" << p.first << ", " << p.second << ")";

}

打印元组的类似结构是什么?


我尝试了各种形式的模板参数堆栈解压缩,传递索引并使用SFINAE来发现何时到达最后一个元素,但是没有成功。我不会因我的密码破译而负担你;希望问题描述很简单。本质上,我想要以下行为:


auto a = std::make_tuple(5, "Hello", -0.1);

std::cout << a << std::endl; // prints: (5, "Hello", -0.1)

奖励积分包括与上一个问题相同的通用水平(char / wchar_t,对定界符)!



萧十郎
浏览 303回答 3
3回答

Cats萌萌

我在C ++ 11(gcc 4.7)中工作正常。我敢肯定,我没有考虑过一些陷阱,但是我认为代码易于阅读并且并不复杂。唯一奇怪的是可以确保我们在到达最后一个元素时终止的“后卫”结构tuple_printer。另一个奇怪的事情可能是sizeof ...(Types),它返回Types类型包中的类型数。它用于确定最后一个元素的索引(大小...(类型)-1)。template<typename Type, unsigned N, unsigned Last>struct tuple_printer {&nbsp; &nbsp; static void print(std::ostream& out, const Type& value) {&nbsp; &nbsp; &nbsp; &nbsp; out << std::get<N>(value) << ", ";&nbsp; &nbsp; &nbsp; &nbsp; tuple_printer<Type, N + 1, Last>::print(out, value);&nbsp; &nbsp; }};template<typename Type, unsigned N>struct tuple_printer<Type, N, N> {&nbsp; &nbsp; static void print(std::ostream& out, const Type& value) {&nbsp; &nbsp; &nbsp; &nbsp; out << std::get<N>(value);&nbsp; &nbsp; }};template<typename... Types>std::ostream& operator<<(std::ostream& out, const std::tuple<Types...>& value) {&nbsp; &nbsp; out << "(";&nbsp; &nbsp; tuple_printer<std::tuple<Types...>, 0, sizeof...(Types) - 1>::print(out, value);&nbsp; &nbsp; out << ")";&nbsp; &nbsp; return out;}
打开App,查看更多内容
随时随地看视频慕课网APP