Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I create a vector of lambdas (of the same type) in C++11?

I was trying to create a vector of lambda, but failed:

auto ignore = [&]() { return 10; };  //1 std::vector<decltype(ignore)> v;     //2 v.push_back([&]() { return 100; });  //3 

Up to line #2, it compiles fine. But the line#3 gives compilation error:

error: no matching function for call to 'std::vector<main()::<lambda()>>::push_back(main()::<lambda()>)'

I don't want a vector of function pointers or vector of function objects. However, vector of function objects which encapsulate real lambda expressions, would work for me. Is this possible?

like image 842
Nawaz Avatar asked Sep 19 '11 21:09

Nawaz


People also ask

What is lambda expression in C++11?

In C++11 and later, a lambda expression—often called a lambda—is a convenient way of defining an anonymous function object (a closure) right at the location where it's invoked or passed as an argument to a function.

What is the type of a lambda function?

The type of a lambda expression is unspecified. But they are generally mere syntactic sugar for functors. A lambda is translated directly into a functor.

Can lambdas be Inlined?

Calls of the lambda are translated to direct calls to its operator() and can therefore be inlined.

How many types of lambda are there?

1) Argument-list: It can be empty or non-empty as well. 2) Arrow-token: It is used to link arguments-list and body of expression. 3) Body: It contains expressions and statements for lambda expression.


1 Answers

Every lambda has a different type—even if they have the same signature. You must use a run-time encapsulating container such as std::function if you want to do something like that.

e.g.:

std::vector<std::function<int()>> functors; functors.push_back([&] { return 100; }); functors.push_back([&] { return  10; }); 
like image 160
Puppy Avatar answered Oct 07 '22 10:10

Puppy