Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

C++ 無名ラムダ式の即時実行

C++無名ラムダ式の即時実行の仕方です。
無名ラムダ式定義し、即時実行しています。
無名ラムダの場合は引数部分を定義する必要はなく、キャプチャする変数の指定だけが必要です。

const std::vector<int> list = { 1, 2, 3 };
const auto sum = [&]() {
    return list[0] + list[1] + list[2];
}();
printf("%d\n", sum);

[&]の部分が全ての変数、ここではlistのみですが、を参照キャプチャすることを表しています。
[&]を[]にすると以下のようにコンパイルエラーとなります。
メッセージを見る限り暗黙的にキャプチャできる場合は省略できそうです。

/Users/pebble8888/develop/a/a/main.cpp:13:16: error: variable 'list' cannot be implicitly captured in a lambda with no capture-default specified
        return list[0] + list[1] + list[2];
               ^
/Users/pebble8888/develop/a/a/main.cpp:11:28: note: 'list' declared here
    const std::vector<int> list = { 1, 2, 3 };
                           ^
/Users/pebble8888/develop/a/a/main.cpp:12:22: note: lambda expression begins here
    const auto sum = []() -> int {
                     ^
/Users/pebble8888/develop/a/a/main.cpp:13:26: error: variable 'list' cannot be implicitly captured in a lambda with no capture-default specified
        return list[0] + list[1] + list[2];
                         ^
/Users/pebble8888/develop/a/a/main.cpp:11:28: note: 'list' declared here
    const std::vector<int> list = { 1, 2, 3 };
                           ^
/Users/pebble8888/develop/a/a/main.cpp:12:22: note: lambda expression begins here
    const auto sum = []() -> int {
                     ^
/Users/pebble8888/develop/a/a/main.cpp:13:36: error: variable 'list' cannot be implicitly captured in a lambda with no capture-default specified
        return list[0] + list[1] + list[2];
                                   ^
/Users/pebble8888/develop/a/a/main.cpp:11:28: note: 'list' declared here
    const std::vector<int> list = { 1, 2, 3 };
                           ^
/Users/pebble8888/develop/a/a/main.cpp:12:22: note: lambda expression begins here
    const auto sum = []() -> int {
                     ^
3 errors generated.

なお、ここではラムダ式の戻り値定義を省略しています。

ラムダ式の即時実行を行うメリットは戻り値の変数をconstにできることです。
このコード以後変更されないことが明確になります。

私がラムダ式を使いたい時はほとんど無名ラムダ式です。
名前付きラムダ式を使いたい場合は関数にした方が見通しが良いので全く使いません。