In the code you posted:
std::function<int(int)> meta_add(int x) { auto add = [x](int y) { return x + y; }; return add; }
The std::function<int(int)> object returned by the function actually contains the moved instance of the lambda function object that was assigned to the local variable add .
When you define a lambda C ++ 11 that captures by value or by reference, the C ++ compiler automatically generates a unique function type, an instance of which is created when the lambda is called or assigned to a variable. To illustrate, your C ++ compiler can generate the following class type for the lambda defined by [x](int y) { return x + y; } [x](int y) { return x + y; } :
class __lambda_373s27a { int x; public: __lambda_373s27a(int x_) : x(x_) { } int operator()(int y) const { return x + y; } };
Then the meta_add function is essentially equivalent:
std::function<int(int)> meta_add(int x) { __lambda_373s27a add = __lambda_373s27a(x); return add; }
EDIT:. By the way, I'm not sure if you know this, but this is an example of the currying function in C ++ 11.
Daniel Trebbien Oct 29 2018-11-21T00: 00Z
source share