I have function at designed to access std::tuple element by index specified in runtime
template
Assuming you pass something similar to a generic lambda, i.e. a function object with an overloaded function call operator:
#include
struct Func
{
template
void operator()(T p)
{
std::cout << __PRETTY_FUNCTION__ << " : " << p << "\n";
}
};
The you can build an array of function pointers:
#include
template struct seq {};
template struct gen_seq : gen_seq {};
template struct gen_seq<0, Is...> : seq {};
template
void apply_one(T& p, F func)
{
func( std::get(p) );
}
template
void apply(T& p, int index, F func, seq)
{
using FT = void(T&, F);
static constexpr FT* arr[] = { &apply_one... };
arr[index](p, func);
}
template
void apply(T& p, int index, F func)
{
apply(p, index, func, gen_seq::value>{});
}
Usage example:
int main()
{
std::tuple t{1, 2.3, 4, 5.6};
for(int i = 0; i < 4; ++i) apply(t, i, Func{});
}
clang++ also accepts an expansion applied to a pattern that contains a lambda expression:
static FT* arr[] = { [](T& p, F func){ func(std::get(p)); }... };
(although I've to admit that looks really weird)
g++4.8.1 rejects this.