Pretty-Printing std::tuple
In a previous question on embellishing STL containers, we successfully developed a comprehensive and graceful solution. This next step delves into the realm of pretty-printing std::tuple using variadic templates (exclusively C 11).
Background
For std::pair, the syntax is straightforward:
std::ostream & operator<<(std::ostream &, const std::pair<S, T> &);
Analogous Construction for Tuple
The puzzle lies in defining an analogous construction for printing a tuple. We aim for this behavior:
auto a = std::make_tuple(5, "Hello", -0.1); std::cout << a << std::endl; // prints: (5, "Hello", -0.1)
Solution
The answer lies in exploiting indices:
namespace aux{ template<std::size_t... Is> struct seq{}; template<std::size_t N, std::size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<std::size_t... Is> struct gen_seq<0, Is...>: seq<Is...>{}; template<class Ch, class Tr, class Tuple, std::size_t... Is> void print_tuple(std::basic_ostream<Ch, Tr>& os, Tuple const& t, seq<Is...>){ using swallow = int[]; (void)swallow{0, (void(os << (Is == 0? "": ", ") << std::get<Is>(t)), 0)...}; } } // aux:: template<class Ch, class Tr, class... Args> auto operator<<(std::basic_ostream<Ch, Tr>& os, std::tuple<Args...> const& t) -> std::basic_ostream<Ch, Tr>& { os << "("; aux::print_tuple(os, t, aux::gen_seq<sizeof...(Args)>()); return os << ")"; }
Bonus: Delimiters
For added flexibility, we provide partial specializations:
// Delimiters for tuple template<class... Args> struct delimiters<std::tuple<Args...>, char> { static const delimiters_values<char> values; }; template<class... Args> const delimiters_values<char> delimiters<std::tuple<Args...>, char>::values = { "(", ", ", ")" }; template<class... Args> struct delimiters<std::tuple<Args...>, wchar_t> { static const delimiters_values<wchar_t> values; }; template<class... Args> const delimiters_values<wchar_t> delimiters<std::tuple<Args...>, wchar_t>::values = { L"(", L", ", L")" };
Conclusion
With the above modifications, pretty-printing std::tuple can be customized to accommodate different character sets and delimiter preferences, offering an elegant and versatile solution.
The above is the detailed content of How can you pretty-print a `std::tuple` using variadic templates in C 11?. For more information, please follow other related articles on the PHP Chinese website!