Skip to content

Instantly share code, notes, and snippets.

@jamesgregson
Last active August 25, 2024 19:51
Show Gist options
  • Save jamesgregson/f6988151c1ca633a55dec2bc5ad23d9e to your computer and use it in GitHub Desktop.
Save jamesgregson/f6988151c1ca633a55dec2bc5ad23d9e to your computer and use it in GitHub Desktop.
C++ output operators for std::array and std::tuple
#pragma once
#include <array>
#include <tuple>
#include <iostream>
// use this namespace to expose operators
namespace ostream_helpers {
namespace {
template< typename T, std::size_t Dim, std::size_t... Is >
void cout_helper( std::ostream& os, const std::array<T,Dim>& in, std::index_sequence<Is...> ){
static_assert( sizeof...(Is) == Dim );
( void( os << std::get<Is>(in) << (Is == sizeof...(Is)-1 ? "" : ", ")), ... );
}
template< typename... Ts, std::size_t... Is >
void cout_helper( std::ostream& os, const std::tuple<Ts...>& in, std::index_sequence<Is...> ){
static_assert( sizeof...(Ts) == sizeof...(Is) );
( void(os << std::get<Is>(in) << (Is == sizeof...(Is)-1 ? "" : ", ")), ... );
}
}
template< typename... Ts >
std::ostream& operator<<( std::ostream& os, const std::tuple<Ts...>& in ){
cout_helper( os, in, std::make_index_sequence<sizeof...(Ts)>() );
return os;
}
template< typename T, std::size_t Dim >
std::ostream& operator<<( std::ostream& os, const std::array<T,Dim>& in ){
cout_helper( os, in, std::make_index_sequence<Dim>() );
return os;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment