In C++, is it possible to map an overloaded function over a heterogenous tuple? For example:
double f(dobule);
size_t f(std::string);
auto t = std::make_tuple(3.14, "a string");
// should be the same as std::make_tuple(f(std::get<0>(t)), f(std::get<1>(t)));
map(f, make_tuple(3.14, "a string")); // type std::tuple<double, size_t>
I can write a map function which maps the same overloaded instance of f
to each tuple element (code below), but I don't see how to defer the overloading resolution of f
from the call to map
to the invocation of f
inside map
. Has anyone figured out how to do this?
Here's my code to map a single instance of an overloaded function over a tuple (where seq and gens are taken from this answer https://stackoverflow.com/a/7858971/431282):
// basically C++14's integer sequence
template<int ...>
struct seq { };
template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> { };
template<int ...S>
struct gens<0, S...> {
typedef seq<S...> type;
};
template<typename R, typename A, typename ...B, int ...S> auto
map_1(R (*f)(A), std::tuple<B...> &&t, seq<S...>)
-> decltype(std::make_tuple(f(std::get<S>(t))...))
{
return std::make_tuple(f(std::get<S>(t))...);
}
template<typename R, typename A, typename ...B> auto
map(R (*f)(A), std::tuple<B...> &&t)
-> decltype(map_1(f, std::forward<std::tuple<B...>>(t), typename gens<sizeof...(B)>::type()))
{
return map_1(f, std::forward<std::tuple<B...>>(t), typename gens<sizeof...(B)>::type());
}