I've been trying to use C++ metaprogramming to build constructs such as
f(g<0>(args...), g<1>(args...), ... g<n-1>(args...))
given callables f
and g
, integer n and variadic arguments args...
However I turn the problem, at some point, I need a nested variadic expansion : one for args... and one for 0 ... n-1, and given the compilation errors I'm getting, I'm wondering if/when it's possible in C++11/14/17, and if not, if there is a clever work-around ?
Below, and example of what I'd like to achieve:
struct add
{
template<int n, class A, class B> static inline auto
f(const A & a, const B & b) -> decltype(std::get<n>(a)+b)
{ return std::get<n>(a) + b; }
};
template<class... Args> void do_stuff(const Args & ... args)
{ /* do stuff with args */ }
std::tuple<char,short,int,float,double> data = {1,3,5};
map_call<3, add>(do_stuff, data, 1); //< what I'm trying to do
// calls do_stuff(add::f<0>(data,2), add::f<1>(data,1), add::f<2>(data,1) )
// i.e. do_stuff(2,4,5)
Where one of the (failed try) implementations of map_call
is given below:
// what I tried:
template<class Mapped, class Indicies> struct map_call_help;
template<class Mapped, int... indices>
struct map_call_help<Mapped, std::integer_sequence<int, indices...>>
{
template<class Callable, class... Args>
static inline void f(Callable && call, Args && ... args)
{
call( Mapped::f<indices>(std::forward<Args>(args)...) ...);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2
// nested expansion fails with parse error / expected ')'
// inner expansion is: std::forward<Args>(args)...
// outer expansion is: Mapped::f<indices>(_forwarded_args_)...
}
};
template<int n, class Mapped, class Callable, class... Args>
inline void map_call(Callable && call, Args && ... args)
{
map_call_help<Mapped, std::make_integer_sequence<int, n>>::f(
std::forward<Callable>(call), std::forward<Args>(args)... );
}
integer_sequence
related stuff needs #include <utility>
and C++14, or it can be implemented in C++11 -- see e.g. answers to this question if interested.