Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a vector of functions (lambdas)

Tags:

c++

c++11

c++14

I have seen how to declare a vector of functions (see calling a function from a vector).

But that answer users pointers. How can I create a vector of functions/lambdas using the new syntax in modern C++?

the examples of functions using the new syntax typically use auto:

auto f = [] (std::string msg) -> void { 
    std::cout << msg << std::endl;
};

What is the actual type of f? so I can declare a vector of this type?

thank you very much for any help

like image 406
dmg Avatar asked Nov 22 '16 07:11

dmg


1 Answers

Use std::function with the corresponding type:

std::vector<std::function<void(void)>> vec;
vec.push_back([]()->void{});

In your case it would be std::function<void(std::string)>.

The exact type of a lambda is meaningless per standard ([expr.prim.lambda]/3):

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type

like image 115
SingerOfTheFall Avatar answered Oct 04 '22 07:10

SingerOfTheFall