Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is every lambda function an anonymous class?

Tags:

c++

c++11

auto a = [](){};
auto b = [](){};
vector<decltype(a)> v;
v.push_back(a); //ok
v.push_back(b); //compiler error

a and b have different type.

I am wondering if each lambda function actually is kind of anonymous class, whenever we create a lambda function, we create a new class with a random name which only visible to compiler ?

like image 764
camino Avatar asked Dec 25 '22 22:12

camino


1 Answers

Yes, every lambda introduces its own unique type.

Now the same lambda can have multiple closures (lambda instances) associated with it in a few ways. C++14 return type deduction is the easiest:

auto nothing() {
  return []{};
}

will always return the same type, but different instances. Similar things can be done by copying a lambda closure, or by passing a lambda in a type deduction context to a template function and storing it.

like image 99
Yakk - Adam Nevraumont Avatar answered Jan 16 '23 04:01

Yakk - Adam Nevraumont