I want a function that will behave like std::transform
for tuples. Basically the functionality to be implemented is
template<size_t From, size_t To, class Tuple, class Func>
void tuple_transform(Tuple&& source, Tuple&& target, Func f)
{
// elements <From, To> of `target` ti become `f(si)`, where
// si is the corresponding element of `source`
};
I believe that to implement this I'll need a compile time integer range struct, a generalization of std::index_sequence
and I've implemented it here with cti::range
. I also believe that this type of compile time traversal is ideal here :
template<class Func, class Tuple, size_t...Is>
void for_each_in_tuple(Func f, Tuple&& tuple, std::index_sequence<Is...>){
using expander = int[];
(void)expander { 0, ((void)f(std::get<Is>(std::forward<Tuple>(tuple))), 0)... };
}
template<class Func, class Tuple>
void for_each_in_tuple(Func f, Tuple&& tuple){
for_each_in_tuple(f, std::forward<Tuple>(tuple),
std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>());
}
Can anyone help me with the implementation ?
Notes : On the type of the mutation function
@MohitJain Like in the code linked (tuple_transform) this is not taken into account (Func
has a single type). If this is solved like that, I could easily extend it by passing a template template parameter template<class> class Func
and mandate that my transformation types are like this
template<typename T>
struct Func
{
static void apply(T& val) { ... }
}
then inside the body of tuple transform, each transformation func could be called like :
get<I>(target) = func<typename tuple_element<I, Tuple>::type>::apply(get<I>(source))
EDIT
Just gave a lightning talk @ accu 2015. The above was the CodeKata at the end of the presentation. I'll leave here the presentation, hopefullly it'll help with any implementation attempts (I think pretty much every tool required is presented, so we'll have more attempts at this)
std::transform
type of each element is same. Instd::tuple
, this type may be different. How do you plan to transform them all with 1 transform function? Is it overloaded, templated? – Thromboembolism