7

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?

1
  • 1
    Have a look at any signals/slots library, such as this, or this, or this. This pattern is completely orthogonal to GUIs, but GUIs are a place where the pattern is commonly used. Commented Apr 5, 2012 at 18:08

2 Answers 2

7

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
});
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

please avoid digraphs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.