c++functionsyntaxinline

How do define anonymous functions in C++?


Can I define functions in C++ inline? I am talking about lambda functions, not the inline keyword that causes a compiler optimization.


Solution

  • C++11 added lambda functions to the language. The previous versions of the language (C++98 and C++03), as well as all current versions of the C language (C89, C99, and C11) do not support this feature. The syntax looks like:

    [capture](parameters)->return-type{body}
    

    For example, to compute the sum of all of the elements in a vector:

    std::vector<int> some_list;
    int total = 0;
    for (int i=0;i<5;i++) some_list.push_back(i);
    std::for_each(begin(some_list), end(some_list), [&total](int x) {
      total += x;
    });