You probably don't need C ++ 17 (which has not yet been released) to get a non-recursive (actually recursive, but more natural) solution. For example, you do not need smoothed expressions and only indexes (C ++ 14) and template parameter packages (C ++ 11) are needed.
#include <iostream> #include <sstream> #include <utility> #include <tuple> #include <string> template<class T> std::ostringstream& concat_to_stream(std::ostringstream &oss, T &&arg) { oss << arg; return oss; } template<class First, class ...Rest> std::ostringstream& concat_to_stream(std::ostringstream &oss, First &&firstArg, Rest &&... restArgs) { oss << firstArg << ", "; return concat_to_stream(oss, std::forward<Rest &&>(restArgs)...); } template<class ...Types> std::string concat_to_string(Types &&... args) { std::ostringstream oss; oss << '['; concat_to_stream(oss, std::forward<Types &&>(args)...); oss << ']'; return oss.str(); } template<class Tuple, size_t... Indices> std::string help_concat(const Tuple &tuple, std::index_sequence<Indices...>) { return concat_to_string(std::get<Indices>(tuple)...); }; template<class ...Types> std::string tuple_to_string(const std::tuple<Types...> &tuple) { return help_concat(tuple, std::make_index_sequence<sizeof...(Types)>{}); }; template<class ...Types> std::ostream &operator<<(std::ostream &os, const std::tuple<Types...> &tuple) { return os << tuple_to_string(tuple); } int main() { std::tuple<int, double, std::string> sample_tuple = std::make_tuple(3, 1.723, "Hi!"); std::cout << sample_tuple << '\n'; // [3, 1.723, Hi!] return 0; }
The recursive part is the concat_to_stream
part, which is quite natural and common. The key part of help_concat
that I learn from Implementing std :: tuple From The Ground Up: Part 6, tuple_cat Take 1 .
The method consists in using the fictitious std::index_sequence
in the parameter list to output size_t... Indices
in the template parameter list, which allows us to "tightly" the contents of std::tuple
into a list of variable parameters, which can be accepted using the concat_to_string
function.
source share