2

我正在尝试编写一个将函数映射到多个迭代器的函数。会是这样的

template <class Fun>
fun_over_variadic_args(Fun fun) { }

template <class Fun, class First, class Rest...> 
fun_over_variadic_args(Fun fun, First& first, Rest&... rest) { 
  fun(first); 
  fun_over_variadic_args(fun, rest...);
}

namespace { 
  template <class T> struct thunk_inc { 
    decltype(T::operator++()) operator()(T& t) { return ++t; } 
  }; 
}

template <class Fun, class MainIterator, class RestOfIterators...>
std::tuple<MainIt&, RestOfIts&...> map_over_iterators(Fun fun, MainIt& it, MainIt& end, RestOfIts&... rest) {
const thunk_inc();
for (; it!=end; fun_over_variadic_args(thunk_inc, it, rest...)) {
      // Do something
    }
}

然后出现的问题是 fun_over_variadic_args 中的函数 Fun 需要模板化,这意味着它不能是 lambda,也不能是需要污染全局命名空间的本地函数对象。

有人知道更好的解决方案吗?
谢谢

编辑:请注意,我想要尽可能快的速度,因此首选保留内联所有函数调用的可能性的解决方案。

Edit2:刚刚意识到我可以使用匿名名称空间将 Fun 函数的范围限制为一个文件。如果存在的话,我仍然很想知道一个更整洁的解决方案。

替代解决方案我发现只要将结果传递给另一个函数,我就可以将函数 fun 应用于可变参数包。因此,如果我有一个函数 fun 想应用于每个参数,我可以做类似的事情

template <class... T>
void foo(T... t) { }

template <class... Arg>
void test(Arg... arg) {
  foo(fun(arg)...); // Works!
  fun(arg)...; // Doesn't work! 
}

澄清替代解决方案然而,使用这个意味着 fun 不能返回 void

4

1 回答 1

1

好吧,鉴于您对问题的额外描述,也许像这样的可变参数会做:

template <typename ItHead, typename... ItTail>
void advance_iterators(ItHead & it, ItTail ...others)
{
  ++it;
  advance_iterators(others...);
}

template <typename It>
void advance_iterators(ItHead & it)
{
  ++it;
}

template <typename Fun, typename ItMain, typename ...ItOthers>
apply_helper(Fun & f, ItMain it, ItOthers ...others)
{
   f(*it);
   apply_helper(f, others...);
}

template <typename Fun, typename ItMain, typename ...ItOthers>
apply_helper(Fun & f, ItMain it)
{
   f(*it);
}

template <typename Fun, typename ItMain, typename ...ItOthers>
apply (Fun & f, ItMain begin, ItMain end, ItOthers ...others)
{
  while (begin != end)
  {
    apply_helper(f, begin, others...);
    advance_iterators(begin, others...);
  }
}

这里明显的限制是Fun必须对迭代器的所有值类型起作用,并且范围必须相等。函数对象是通过引用传递的,你可以根据自己的喜好进行修改。

Update: If I misunderstood and you want f to operate on all values simultaneously, then you should get rid of apply_helper and just call f(begin, others...) and make a function f that takes all those iterators.

于 2011-06-14T20:45:59.387 回答