2016-12-15 18 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

看看第一個線程:) –