参数类型模板类型中的通用 lambda auto

generic lambda auto in parameter type template type

我想弄清楚为什么 clang 没有编译这段代码:

#include <vector>
#include <iostream>

int main() {
    auto lambda = [](const std::vector<auto>& x){
        std::cout << x.front() << x.back() << std::endl;
    };
    lambda(std::vector<int>(1,1));
}

根据这个 post C++14 标准不允许它,但我找不到任何来源来支持它。 我对标准的相应部分的理解是,应该允许这个特性(第 5.1.2 章第 5 条指出每个 auto 都被翻译成一个模板参数,与精确定位无关 (引用:consists of one invented type template-parameter for each occurrence of auto in the lambda’s parameter-declaration-clause)。

为避免以后出现任何问题:不,我没有实际的标准,但使用较早的草案 (N3797)。我希望他们没有删除我的解释。

谢谢!

您对标准的误解与 parameter-declaration-clause 允许的内容有关。它是 parameter-declaration 的列表。这涉及到很多复杂的语法。

但是解开那个复杂语法的最终结果是 auto 不能用在 template-argument-list 中。这就是您在使用 vector<auto>.

时要尝试做的事情

所以 5.1.2 是无关紧要的,因为语法 auto 只是 不能 放在那里。

"generic lambda" 定义在 [dcl.spec.auto]/3:

If the auto type-specifier appears as one of the decl-specifiers in the decl-specifier-seq of a parameter-declaration of a lambda-expression, the lambda is a generic lambda.

const std::vector<auto>& x 中的 auto 不是“decl-specifier 之一 在 decl-specifier-seq”中,因此 [](const std::vector<auto>& x){ } 不是 "generic lambda"。相反,根据 [dcl.spec.auto]/6:

A program that uses auto or decltype(auto) in a context not explicitly allowed in this section is ill-formed.