Reputation: 323
I have a pointer to std::function
that stores lambda inside.
How can I call that lambda?
example:
std::function <void()>* fx = new std::function <void()>([] {std::cout << "Hello world;\n"; });
//here i need to call my fx, just fx(); does not works in this case
fx
may be stored inside std::pair
Upvotes: 1
Views: 153
Reputation: 32722
You can call it either of the following ways:
Dereferencing the pointer and call
(*fx)();
or explicitly calling the
std::function<R(Args...)>::operator()
fx->operator()(); // explicitly calling the `operator()`
or using
std::invoke
std::invoke(*fx); // needed C++17 or later
However, you should be re-think about using a pointer to the std::function
, which is normally not required.
fx
may be stored insidestd::pair
This does not actually matter, as you need to first get the pair's element (i.e. pair.first
or pair.second
) and call the stored lambda, as mentioned above. For instance, if the pair.second
is your fx
(*pair.second)();
Upvotes: 4