Re: Defect Report: tuple::tail() should be in the public interface
Joe Gottman <jgottman@carolina.rr.com> wrote:
As std::tuple is currently written, it is difficult to impossible to
write functions that take a tuple of indeterminate size as a parameter
and make use of the entire tuple. For example, consider a function that
writes the contents of a tuple to a stream.
template <class... Types>
inline ostream &print_tuple(ostream &os, const tuple<Types...> &tup);
It is impossible to use a for-loop and tuple::get to write this
function, because tuple::get<N> requires N to be a compile-time constant
while a for-loop requires N to be a variable. The programmer would have
to write an implementation function templated on an int and the Types:
gee some simple template programming does this assuming an
std::ostream & operator << (std::ostream &,const T &); exists
for each type in the tuple.
template <int N,int M, class T>
struct printer_unit
{
static std::ostream do_it(std::ostream &os,const T &t)
{
os << std::tr1::get<N>(t);
return printer_unit<N+1,M,T>::do_it(os,t);
}
};
template <int N,class T>
struct printer_unit<N,N,T>
{
static std::ostream & do_it(std::ostream &os,const T &t)
{
return os;
}
};
template <class T>
inline
std::ostream & print_tuple(std::ostream &os,const T &t)
{
return printer_unit
<
0,
std::tr1::tuple_size<T>::value,
T
>::do_it(os,t);
}
and no copies of the tuple are needed. A similiar approach can handle
other iteration of a tuple.
A general approach is to construct an mpl sequence from tuple_size<> and
tuple_element<> and creating a boost::variant from that sequence. You
could convert the tuple to an stl::container of the variant type and
just use ordinary algorithms, providing a functor that handles all types
passed. or just do above and pass get<N>(t) to the functor/function
like above.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]