应该如何传递函数指针或函数对象?

时间:2014-04-23 20:21:01

标签: c++

每当我看到以function为模板参数的函数时,它会按值function对象。

E.g。来自for_each reference

template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function fn)
{
  while (first!=last) {
    fn (*first);
    ++first;
  }
  return fn;      // or, since C++11: return move(fn);
}

1)为什么会这样?

你可以传递很多东西,原始函数,lambda函数,std :: function,functor ......所以对象可能非常大(特别是std :: function或者functor)并且传递值并不理想。但引用说,fn必须是function pointer or a move constructible function object

struct FunctorNMC //non-move-constructible
{
    FunctorNMC() = default;
    FunctorNMC(FunctorNMC&&) = delete;

    void operator()(int a) const { std::cout << a << " ";   }
};

无法调用:

std::vector<int> v{1,2,3};
for_each(v.begin(), v.end(), FunctorNMC());
VS2013中的

可以像:

一样调用
FunctorNMC tmp;
my_for_each(v.begin(), v.end(), tmp);

但是IDEONE会出错。

2)为什么?如果我有仿函数,由于某种原因不支持move

,该怎么办?

3)不应该将功能视为Function && fn

4)可以通过值传递的函数对象(不移动)?

IDEONE项目如果需要可以玩。

0 个答案:

没有答案