Search code examples
c++c++11lambdastd-functionfunction-call

How to call the lambda stored in pointer to the `std::function`?


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


Solution

  • You can call it either of the following ways:

    1. Dereferencing the pointer and call

      (*fx)();
      
    2. or explicitly calling the std::function<R(Args...)>::operator()

      fx->operator()();  // explicitly calling the `operator()`
      
    3. 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 inside std::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)();