Listing 8
#include <tuple>
#include <iomanip>
#include <iostream>
#include <ostream>
using std::tr1::tuple; using std::tr1::get; using std::tr1::tuple_size;
using std::tr1::make_tuple;
using std::basic_ostream; using std::cout; using std::boolalpha;
template <int N> struct writer;
template <> struct writer<0>
{ // handle empty tuple types
template <class Ostr, class Tuple>
static Ostr& put(Ostr& str, const Tuple& tpl)
{ // show contents
return str;
}
};
template <> struct writer<1>
{ // show first element of tuple object
template <class Ostr, class Tuple>
static Ostr& put(Ostr& str, const Tuple& tpl)
{ // show contents
return str << get<0>(tpl);
}
};
template <int N> struct writer
{ // show first N elements of tuple object
template <class Ostr, class Tuple>
static Ostr& put(Ostr& str, const Tuple& tpl)
{ // show contents
return writer<N-1>::put(str, tpl)
<< ", " << get<N-1>(tpl);
}
};
template <class Tuple, class Char, class Traits>
basic_ostream<Char, Traits>& write_tuple(
basic_ostream<Char, Traits>& str, const Tuple& tpl)
{ // show contents
return writer<tuple_size<Tuple>::value>::put(str, tpl);
}
int main()
{ // demonstrate simple meta-programming technique
cout << boolalpha;
write_tuple(cout, make_tuple(1, 2.0, 3.3, true));
cout << '\n';
return 0;
}