Possible Duplicate:
Pretty-print std::tuple
In a database library (soci), there is a chunk of code below that works on std::tuple<>
's from one to ten parameters.
static class methods from_base()
and to_base()
are implemented for arguments of 1-tuple to 10-tuple.
The guts essentially stream every n-tuple element to and from the passed-in stream. Everything is hard-coded.
How can this code be translated to use C++11's variadic templates instead (no limit on parameters)? Actually using variadic templates or not is secondary. What we really want to do is replace the hard-coding with the general case of n-tuple argument.
Part of the problem is, there is, technically, only one argument, but that argument is an n-tuple, so I can't quite use what is described here in Wikipedia. What is the best approach?
#include "values.h"
#include "type-conversion-traits.h"
#include <tuple>
namespace soci
{
template <typename T0>
struct type_conversion<std::tuple<T0> >
{
typedef values base_type;
static void from_base(base_type const & in, indicator ind,
std::tuple<T0> & out)
{
in
>> std::get<0>(out);
}
static void to_base(std::tuple<T0> & in,
base_type & out, indicator & ind)
{
out
<< std::get<0>(in);
}
};
template <typename T0, typename T1>
struct type_conversion<std::tuple<T0, T1> >
{
typedef values base_type;
static void from_base(base_type const & in, indicator ind,
std::tuple<T0, T1> & out)
{
in
>> std::get<0>(out)
>> std::get<1>(out);
}
static void to_base(std::tuple<T0, T1> & in,
base_type & out, indicator & ind)
{
out
<< std::get<0>(in)
<< std::get<1>(in);
}
};
// ... all the way up to 10 template parameters
}
RUNNABLE ANSWER (based on Grizzly's post below)
#include <iostream>
#include <tuple>
using namespace std;
// -----------------------------------------------------------------------------
template<unsigned N, unsigned End>
struct to_base_impl
{
template<typename Tuple>
static void execute(Tuple& in, ostream& out)
{
out << std::get<N>(in) << endl;
to_base_impl<N+1, End>::execute(in, out);
}
};
template<unsigned End>
struct to_base_impl<End, End>
{
template<typename Tuple>
static void execute(Tuple& in, ostream& out)
{
out << "<GAME OVER>" << endl;
}
};
// -----------------------------------------------------------------------------
template <typename Tuple>
struct type_conversion
{
static void to_base(Tuple& in, ostream& out )
{
to_base_impl<0, std::tuple_size<Tuple>::value>::execute(in, out);
}
};
template <typename... Args>
struct type_conversion<std::tuple<Args...>>
{
static void to_base(std::tuple<Args...>& in, ostream& out )
{
to_base_impl<0, sizeof...(Args)>::execute(in, out);
}
};
// -----------------------------------------------------------------------------
main()
{
typedef tuple<double,int,string> my_tuple_type;
my_tuple_type t { 2.5, 5, "foo" };
type_conversion<my_tuple_type>::to_base( t, cerr );
}