0

在 C++ 中,是否可以在异构元组上映射重载函数?例如:

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>

我可以编写一个映射函数,将相同的重载实例映射f到每个元组元素(下面的代码),但我不知道如何将重载解析f从调用推迟map到调用finside map。有没有人想出如何做到这一点?

这是我将重载函数的单个实例映射到元组上的代码(其中 seq 和 gens 取自此答案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());
}
4

1 回答 1

2

问题是它不能单独使用函数指针来完成,因为你想在函数重载绑定到参数时解决它。如果不执行重载解析,您将无法获得指向函数的函数指针。关键是提供一个在调用时执行重载的函数对象,而不是在开始时尝试获取函数指针。

为此,我将主要功能声明为

template<typename Func, typename ...B> auto
map(Func&& f, std::tuple<B...> &&t)
  -> decltype(map_1(std::forward<Func>(f), std::forward<std::tuple<B...>>(t), typename gens<sizeof...(B)>::type()))
{
  return map_1(std::forward<Func>(f), std::forward<std::tuple<B...>>(t), typename gens<sizeof...(B)>::type());
}

然后map_1以类似的方式定义。

然后你可以制作一个函数对象包装器

struct Wrapper
{
   template<typename T>
   auto operator()(T&& t) const -> decltype( f(std::forward<T>(t)) )
   {
       return f(std::forward<T>(t));
   }
};

并调用它map(Wrapper(), make_tuple(3.14, "a string"))

编辑:如果您有 C++14,您可以执行以下操作(感谢@MooingDuck 的启发)

#define BINDOVERLOADED(X) [](auto&& t) { return X(std::forward<decltype(t)>(t)); }
auto x = map(BINDOVERLOADED(f), make_tuple(3.14, "a string"));

http://coliru.stacked-crooked.com/a/439f958827de8cf2

于 2014-05-01T19:12:17.867 回答