April 2013

Quick Q: How to accept lambdas as callbacks? -- StackOverflow

The poster is definitely thinking along the right lines -- anything callable that would have accepted a pointer to function and/or functor in C++98 should be written to be able to accept a lambda function in modern C++.

So what about callbacks as a specific example?

Passing and storing lambda function as callbacks

I was wondering if this would be an accepted approach to writing callbacks:

Storing callbacks:

struct EventHolder {
    std::function<void()> Callback;
    EventTypes::EventType Type;
};
std::vector<Events::EventHolder> EventCallbacks;

Method definition:

void On(EventType OnEventType,std::function<void()>&& Callback)
{
    Events::EventHolder NewEvent;
    NewEvent.Callback=std::move(Callback);
    NewEvent.Type=OnEventType;
    EventCallbacks.push_back(std::move(NewEvent));
}

Binding event:

Button->On(EventType::Click,[]{
    // ... callback body
});

My biggest question would be regarding passing the Callback by value. Is this a valid approach?