Nordlöw
Nordlöw

Reputation: 12138

C++11 Lambda Expressions as Callback Functions

Does any C++ GUI toolkit out there support definition of callback functions as C++11 lambda expressions? I believe this is a unique pro of using C# (compared to C++ at least) for writing GUI-based programs. What type signature should I use for functions taking lambda expressions as arguments and how does these support implicit conversions?

Upvotes: 7

Views: 9225

Answers (2)

bames53
bames53

Reputation: 88225

Does any C++ GUI toolkit out there support definition of callback functions as C++11 lambda expressions?

If they accept function pointers then you can at least use lambdas that don't capture anything. Such lambdas can be automatically converted to function pointers.

What type signature should I use for functions taking lambda expressions as arguments and how does these support implicit conversions?

If you want people to use lambdas or any callable object then you could either have your API accept std::function objects, or use a template:

template<typename Callback>
void do_it(Callback c) {
    c();
}

do_it([&]{ c = a+b; });

A template will allow the lambda to be inlined while std::function require indirection. This may not matter much for GUI callbacks.

Upvotes: 5

Paul Michalik
Paul Michalik

Reputation: 4381

The answer to second part of the question: You could use std::function<Signature> where Signature = e.g. void (int) or - if the lambdas don't take closures - the good old void (Foo*)(int) method, since a lambda without a closure must be convertible to proper function type. So, for example a call to a method with signature:

void AddHandler(std::function<void (int)> const &);

could look like this:

myObject.AddHandler([&](int _) {
    // do something and access captured variables by reference
});

Upvotes: 7

Related Questions