什么时候使用lambdas上的函子 [英] When to use functors over lambdas
问题描述
有没有一种情况,创建一个函数比使用lambda更有意义?
Is there ever a situation where it makes more sense to create a functor than to use a lambda?
我知道我的问题实际上是何时在函子上使用lambda ,但我不能想到一个情况实践,其中函子将优先于超过lambda。对此有任何想法吗?
I know my question is effectively the reverse of when to use a lambda over a functor, but I can't think of a situation in practice where a functor would be preferred over a lambda. Any thoughts on this?
推荐答案
lambda是一个函数 - 只是用较短的语法定义。
A lambda is a functor - just defined with a shorter syntax.
问题是这种语法是有限的。它不总是允许你以最有效和灵活的方式解决问题 - 或者。直到C ++ 14,运算符()
甚至不能是模板。
The problem is that this syntax is limited. It doesn't always allow you to solve a problem in the most efficient and flexible way - or at all. Until C++14, the operator()
couldn't even be a template.
只有一个 operator()
。您不能提供几个重载来区分,例如,参数的类型:
Furthermore, a lambda has exactly one operator()
. You can't provide several overloads to distinguish between, say, the types of the arguments:
struct MyComparator
{
bool operator()( int a, int b ) const {return a < b;}
bool operator()( float a, float b ) const {return /*Some maths here*/;}
};
..或对象参数的值类别(即被调用的闭包对象)。你也可以不定义特殊成员函数,包括构造函数和析构函数 - 如果函子负责资源怎么办?
.. or value category of the object argument (that is, the closure object that is called). You can also not define special member functions, including constructors and destructors - what if a functor shall be responsible for resources?
lambdas的另一个问题是它们不能递归。当然,正常的函数(包括操作符函数)可以是。
Another problem with lambdas is that they cannot be recursive. Of course, normal functions (including operator functions) can be.
还要考虑到,lambdas不能用作相关容器的比较器或智能指针的删除器: t直接传递闭包类型作为模板参数,并需要从另一个闭包对象构造容器成员。 (Closure类型没有默认构造函数!)。对于块范围映射
,这不是一个麻烦:
Also consider that lambdas are unhandy to use as comparators for associative containers or deleters for smart pointers: You can't directly pass the closure type as a template argument and need to construct the containers member from another closure object. (Closure types don't have a default constructor!). For a block-scope map
that isn't too much of a hassle:
auto l = [val] (int a, int b) {return val*a < b;};
std::map<int, int, decltype(l)> map(l);
现在,如果 map
?什么模板参数,什么初始化在构造函数初始化列表中?你必须使用另一个静态数据成员 - 但是因为你必须在类定义之外定义一个可以说是丑陋的类。
Now, what happens if your map
is a data member? What template argument, what initializer in the constructors initialization list? You'd have to use another static data member - but since you have to define it outside the classes definition that is arguably ugly.
总结:Lambdas对于更复杂的场景不是有用的,因为它们不是为他们制作的。它们提供了一种简单和简洁的方法来为相应的简单情况创建简单函数对象。
这篇关于什么时候使用lambdas上的函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!