Search code examples
c++c++11std-function

Forward arguments of std::function given as an argument to new object


Here is my problem: I would like to create a std::function object which will "extract" a part of its argument and pass that to a different std::function object.

I need a function like this:

std::function<void(Event)> MakeEventCallback(std::function<void(std::shared_ptr<Input>&)>);

Call to this potential function:

some_global_callbacks.push_back(MakeEventCallback(
  [](std::shared_ptr<Input>& input){ /*do stuff with input object;*/ input->DoStuff();}
));

some_global_callbacks is eventually processed like this:

auto event = createEvent(...);
for (auto eventCallback : some_global_callbacks)
{
  eventCallback(event);
}

The constructor of Event takes a std::shared_ptr<Input>, which can also be retrieved from the Event using Event::getOriginalInput.

I want the invocation of eventCallback to invoke the original callback passed to MakeEventCallback with the appropriate input.


Solution

  • Based on our discussion in chat, I believe you're looking for this:

    std::function<void(Event&)> MakeEventCallback(std::function<void(std::shared_ptr<Input>&)> callback)
    {
      return [callback](Event& ev) { callback(ev.getOriginalInput()); };
    }
    

    This will create a "wrapper" callback which takes an Event, extracts the Input from that Event, and passes the Input to the original callback.