Pretty Printing std::tuple
In a previous question, we discussed a general solution for pretty-printing STL containers. Now, let's extend that solution to handle std::tuple using variadic templates (C 11 or later).
Analogous Construction for Printing a Tuple
Similar to std::pair, pretty-printing a tuple involves enclosing the elements within parentheses and separating them with commas. The goal is to achieve the following behavior:
auto a = std::make_tuple(5, "Hello", -0.1); std::cout << a << std::endl; // prints: (5, "Hello", -0.1)
Variadic Solution
To accomplish this, we utilize variadic templates along with a helper struct for generating a sequence of indices. Here's the solution:
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 << ")"; }
This solution elegantly prints tuples using comma-separated elements enclosed in parentheses.
Custom Delimiters
For added flexibility, you can include custom delimiters for tuples by adding the following 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")" };
By incorporating these specializations, you can customize the delimiters for std::tuple as well.
The above is the detailed content of How can I pretty-print a std::tuple using variadic templates in C ?. For more information, please follow other related articles on the PHP Chinese website!