C++11 和缺少多态 lambda - 为什么?

2022-01-24 00:00:00 lambda standards polymorphism c++ c++11

我一直在审查 C++11 的草稿版本标准.特别是关于 lambdas 的部分,我对不引入多态 lambdas 的原因感到困惑.

I've been reviewing the draft version of the C++11 standard. Specifically the section on lambdas, and I am confused as to the reasoning for not introducing polymorphic lambdas.

例如,在可以使用多态 lambda 的 100001 种方式中,我曾希望我们可以使用如下代码:

For example, amongst the 100001 ways polymorphic lambdas could be used, I had hoped we could use code such as the following:

template<typename Container>
void foo(Container c)
{
    for_each(c.begin(), c.end(), [](T& t) { ++t; });
}

原因是什么:

  • 是委员会没时间了吗?

  • Was it that the committee ran out of time?

多态 lambda 太难实现了?

That polymorphic lambdas are too hard to implement?

或者也许他们被认为是 PTB?

Or perhaps that they are seen as not being needed by the PTB?

注意:请记住上面的例子不是唯一的,它只是作为代码类型的指南.仅专注于为上述代码提供解决方法的答案将不被视为有效!

Note: Please remember the example above is not the only one, and it is only provided as a guide to the types of code. Answers that solely concentrate on providing a workaround for the above piece of code will not be considered as valid!

相关来源:

  • Lambda 表达式和闭包对于 C++(文档编号 N1968=06-0038)
  • 可以对 lambda 函数进行模板化吗?

推荐答案

我们没有多态 lambda 的原因在 此帖子.

The reason we don't have polymorphic lambdas is explained pretty well in this posting.

这与从 C++11 中提取的概念特性有关:本质上,多态 lambda 是普通的、不受约束的函数模板,我们不知道如何对使用不受约束的模板的概念约束模板进行类型检查.然而,解决这个问题很容易,如下所示这里(死链接),所以我认为没有任何障碍.

It has to do with the concepts feature that was pulled from C++11: essentially, polymorphic lambdas are ordinary, unconstrained function templates and we didn't know how to typecheck a concept-constrained template that used an unconstrained template. However, solving that problem turns out to be easy as shown here(dead link), so I don't think there's any obstacle remaining.

cpp-next 的链接已失效;相关信息可见 这里

The link to cpp-next is dead; the relevant info can be found here

相关文章