Can anyone explain how lambda functions are represented in std::function? Is there an implicit conversion by the compiler and std::function used as a container?
I recently asked a slightly different question, which was marked as a duplicate of this question. The answer is the type of a lambda function is not defined and unspecified. I have found some code that appears to provide a container for the lambda function as follows below. I have also included a Stroustrup quote, which seems to contradict that lambda functions do not have a type defined, saying however it is a function closure type. This is only confusing the matter further.
Update: Partial answer regarding implementation of function<> is here.
Appreciate your guidance.
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
static vector<function<void(int)>> cbl;
static vector<function<int(int)>> cblr;
class GT {
public:
int operator()(int x) {return x;}
};
void f()
{
auto op = [](int x) {cout << x << endl;};
cbl.push_back(op);
for (auto& p : cbl)
p(1);
auto op2 = [](int x) {return x;};
cblr.push_back(op2);
cblr.push_back(GT());
for (auto& p : cblr)
cout << p(99) << endl;
}
int main(int argc, char *argv[])
{
f();
return 0;
}
Compilation and result:
g++ -pedantic -Wall test130.cc && ./a.out
1
99
99
Stroustrup talks about this in C++ 4th Ed Page 297:
To allow for optimized versions of lambda expressions, the type of a lambda expression is not defined. However, it is defined to be the type of a function object in the style presented in §11.4.1. This type, called the closure type, is unique to the lambda, so no two lambdas have the same type. Had two lambdas had the same type, the template instantiation mechanism might have gotten con- fused. A lambda is of a local class type with a constructor and a const member function operator()().