每当我看到以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项目如果需要可以玩。