Lambda 函数作为基类
问题描述
在使用 Lambda 时,我发现了一个我不完全理解的有趣行为.
Playing around with Lambdas I found an interesting behaviour that I do not fully understand.
假设我有一个从 2 个模板参数派生的 struct Overload
,并且有一个 using F1::operator();
子句.
Supose I have a struct Overload
that derives from 2 template parameters, and has a using F1::operator();
clause.
现在如果我从两个函子派生,我只能访问 F1 的 operator()(正如我所期望的)
Now if I derive from two functors I can only access the operator() of F1 (as I would expect)
如果我从两个 Lambda 函数派生,这将不再正确:我也可以从 F2 访问 operator().
If I derive from two Lambda Functions this is no longer true: I can access the operator() from F2 too.
标准规定:
lambda 表达式的类型(也是闭包对象的类型)是唯一的、未命名的非联合类类型
The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non- union class type
所以每个 Lambda 的类型都应该是唯一的.
So every Lambda's types should be unique.
我无法解释为什么会这样:有人能解释一下吗?
I cannot explain why this is so: can anyone shed some light on this please?
推荐答案
除了 operator()
之外,由 lambda 定义的类可以(在适当的情况下)提供到指向函数的指针.情况(或至少是主要情况)是 lambda 无法捕获任何内容.
In addition to operator()
, a the class defined by a lambda can (under the right circumstances) provide a conversion to a pointer to function. The circumstance (or at least the primary one) is that the lambda can't capture anything.
如果您添加捕获:
...不再提供到 pointer to function
的转换,因此尝试编译上面的代码会给出您可能一直期望的错误:
...the conversion to pointer to function
is no longer provided, so trying to compile the code above gives the error you probably expected all along:
这篇关于Lambda 函数作为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!