C++ 11: lexical closure in lambda function, example 1

In functional programming (FP), there are some important features:

  1. First class function.
  2. Lambda function.
  3. Lexical closure.

This can be found in Lisp, Ruby ... but not C++, or Java, in the past.

Now C++ 11 has arrived, and this can be easily implemented in C++ too.

Let me show you an example:

#include <iostream>
#include <functional>
auto makeAdder = [](int n) {
  return [=](int val) { return val + n; };
};

int main() {
  int n = 0;
  std::cin >> n;
  auto addn = makeAdder(n);
  std::cout << addn(4) << std::endl;
  return 0;
}
Compile:

g++ -std=c++11 example1.cpp -o example1
Run:

./example
Input 1, print 5 .

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章