yohhoyの日記

技術的メモをしていきたい日記

C++11ラムダ式のパラメータ宣言部は省略可能

タイトル通り。下記コードの(1), (2), (3)は等価。

[](){ /*...*/ }  // (1)
[]{ /*...*/ }    // (2)
[]() -> void { /*...*/ }  // (3)

[] -> void { /*...*/ }    // ill-formed

ただし、(1)および(2)で戻り値型がvoidに推論されるのは、ラムダ式の本体部が{ return expression ; }の形ではない場合のみ。
2021-09-11追記:C++2b(C++23)に向けてP1102R2が採択され[] -> voidもwell-definedとなる予定。C++11以降のラムダ式仕様の変遷は https://zenn.dev/yohhoy/scraps/d7d861903237b5 を参照。

下記、N3290 5.1.2 Lambda expressionsより部分引用。

lambda-expression:
 lambda-introducer lambda-declaratoropt compound-statement
lambda-introducer:
 [ lambda-captureopt ]
lambda-declarator:
 ( parameter-declaration-clause ) mutableopt
  exception-specificationopt attribute-specifier-seqopt trailing-return-typeopt

ラムダ式の戻り値型を宣言するtrailing-return-typeは、8 Declarators/p4で定義される。

trailing-return-type:
 -> trailing-type-specifier-seq abstract-declaratoropt