lambda capture during initialization should be an error

前端 未结 1 642
栀梦
栀梦 2021-01-19 21:52

What I\'m trying to do is eat exceptions when constructing an object that may be invalid. It\'d be perfect for use of std::optional, but I don

1条回答
  •  爱一瞬间的悲伤
    2021-01-19 22:29

    The second snippet runs into [dcl.spec.auto]/10:

    If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed.

    The type of foo is needed to determine the type of the expression foo within the lambda body, but at that point you haven't deduced foo's type yet, so the program is ill-formed.


    As to why you are allowed to capture something before its initialization, see generally Why is 'int i = i;' legal?. We have many examples of recursive lambdas using std::function:

    std::function foo = [&foo](int i){ return foo(i - 1); };
    

    0 讨论(0)
提交回复
热议问题