Boost logo

Boost :

From: Daniel Frey (d.frey_at_[hidden])
Date: 2008-07-19 06:36:36


While playing with GCC 4.3 and variadic templates, I came across the
following problem: Say I have to write a function that takes a tuple as
a parameter and needs to call another function with the expanded tuple.
In code:

template< typename... Ts >
void f( const std::tuple< Ts... >& tp )
{
  g( tp... );
}

OK, tp... doesn't work. Next try:

template< typename... Ts >
void f( const std::tuple< Ts... >& tp )
{
  g( std::get< Ns >( tp )... );
}

That doesn't work either, but it's close, except that I only have Ts,
not Ns (which need to expand from 0 to sizeof...( Ts ) - 1. Doug Gregor
pointed me to N2080, which inspired me to create a light-weight general
helper for cases where you need indices instead of types (or both).
Here's the code that actually works:

template< typename... Ts, std::size_t... Ns >
void fimpl( const std::tuple< Ts... >& tp, const indices< Ns... >& )
{
  g( std::get< Ns >( tp )... );
}

template< typename... Ts >
void f( const std::tuple< Ts... >& tp )
{
  fimpl( tp, typename make_indices< sizeof...( Ts ) >::type() );
}

with the following helpers:

template< std::size_t... Ns >
struct indices
{
};

template< std::size_t N, std::size_t... Ns >
struct make_indices
{
  typedef typename make_indices< N - 1, N - 1, Ns... >::type type;
};

template< std::size_t... Ns >
struct make_indices< 0, Ns... >
{
  typedef indices< Ns... > type;
};

While I appreciate any feedback/improvement/... on the specific
problem/solution, there's also another issue here: These helpers are
useful only for C++0x - I don't see how they could make any sense for
the current C++ standard.

There seem to be three options:

a) Consider them an internal, undocumented implementation detail that
other Boost libraries may use. No problem here, could be done today if
there is interest.

b) Make them part of the MPL. My gut feeling is that this is the wrong
place - they don't belong to meta-programming because (as the example
shows) they are useful in a variety of contexts.

c) Make them a user-visible, documented feature of Boost. They are
rather small so I'd compare them to next/prior: Not worth to be a
full-fledged Boost library, but maybe part of Boost.Utilities.

Thoughts?

Regards, Daniel


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk