Skip to content

Instantly share code, notes, and snippets.

@lanesurface
Created June 26, 2020 03:43
Show Gist options
  • Save lanesurface/59fbce0ce05f90ff0bfbb0767d05be57 to your computer and use it in GitHub Desktop.
Save lanesurface/59fbce0ce05f90ff0bfbb0767d05be57 to your computer and use it in GitHub Desktop.
/*
* FILE: print_tuple.cpp
* DESCRIPTION: Print the contents of a std::tuple<>.
* DATE: 06/25/2020
*/
#include <iostream>
#include <tuple>
template <int I=0, typename ...T>
void print_tuple(
std::ostream& stream,
std::tuple<T...>& tup)
{
const size_t tup_size=sizeof...(T);
if constexpr (I<tup_size) {
stream << std::get<I>(tup);
print_tuple<I+1>(stream, tup);
}
}
int main() {
auto my_tuple=std::make_tuple(0,0,0);
print_tuple(std::cout, my_tuple);
return 0;
}
@lanesurface
Copy link
Author

Another way to generate the calls to std::get which avoids recursion is shown below.

template <typename T, size_t ...Is>
static void print_tuple_impl(
  T&& tuple,
  std::index_sequence<Is...>)
{
  ((std::cout << std::get<Is>(tuple) << ' '), ...); // C++17 fold expression using operator `,`.
} 

template <typename ...T>
void print_tuple(std::tuple<T...>& tuple) {
  print_tuple_impl(tuple, std::make_index_sequence<sizeof...(T)>{});
}

This avoids the overhead of generating the recursive template function, which grows in proportion to the size of the tuple being printed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment