2016-12-15 20 views
12
int main() 
{ 
    auto l = [x = 10]() -> decltype(x) {}; 
} 

这是一个错误还是标准中有某些东西可以显式地阻止在lambda的尾随返回类型中使用用C++ 14通用语法捕获的对象?


注意,两种编译器很高兴与非广义捕获:

int main() 
{ 
    int x = 10; 
    auto l = [x]() -> decltype(x) { return 0; }; 
} 
+3

'int'曾经是一个默认的返回类型,gcc会推导出其他类型吗? – alexeykuzmin0

+0

@ alexeykuzmin0:很好。 [它始终“推断”'int'](http://melpon.org/wandbox/permlink/OivD8IYUT3Jq0720)...更新问题 –

+2

有一些奇怪的例子,例如decltype和lambda, [本](https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/6-VL5bzK6Ik)。 – TartanLlama

回答

8

TL; DR:编译器像预期的那样。

该标准定义的λ语义如下[expr.prim.lambda,部分1]:

lambda-expression:

lambda-introducer lambda-declarator_opt compound-statement 

这里化合物语句之间{}拉姆达的只是身体,因为其他一切被包括在拉姆达说明符

lambda-declarator:

(parameter-declaration-clause) decl-specifier-seq_opt 
     exception-specification_opt attribute-specifier-seq_opt trailing-return-type_opt 

此外,在同一章的第12条,它说,

An init-capture behaves as if it declares and explicitly captures a variable of the form “auto init-capture ;” whose declarative region is the lambda-expression’s compound-statement, except that:

(12.1) — if the capture is by copy (see below), the non-static data member declared for the capture and the variable are treated as two different ways of referring to the same object, which has the lifetime of the non-static data member, and no additional copy and destruction is performed, and

(12.2) — if the capture is by reference, the variable’s lifetime ends when the closure object’s lifetime ends.

因此,在您的第一个示例中,变量x作用域仅为lambda体,不包括decltype表达式。在第二个例子中,显然,x范围是功能main

+1

谢谢。这有点烦人,但确实有道理。我想知道规则是否可以放宽,以在尾部返回类型的范围中引入'x' ... –

+0

@VittorioRomeo考虑在论坛上创建主题:https://isocpp.org/forums/iso-c-standard -future-proposals – alexeykuzmin0

+0

看看第一个线程:) –