Now that Qt5 supports connecting signals to lambda functions, I would like to be able to pass a lambda as an argument to another function. I've got a function that looks something like this:
void SomeFunc(Functor f)
{
connect(obj, &MyObject::someSignal, f);
}
However, the compiler complains when I do that:
"Functor" has not been declared
Changing Functor
to QtPrivate::Functor
yields:
QtPrivate::Functor is not a type
Basically, all I want to do is pass the argument that QObject::connect
is going to get to my function. What type do I need to use?
A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You can pass values from the current scope to a lambda expression. The RemoveHandler statement is an exception.
Permalink. All the alternatives to passing a lambda by value actually capture a lambda's address, be it by const l-value reference, by non-const l-value reference, by universal reference, or by pointer.
A lambda expression with an empty capture clause is convertible to a function pointer. It can replace a stand-alone or static member function as a callback function pointer argument to C API.
There are two options:
template<typename Functor>
void SomeFunc(Functor f)
{
connect(obj, &MyObject::someSignal, f);
}
or
void SomeFunc(std::function<void(/*ArgumentTypes...*/)> f)
{
connect(obj, &MyObject::someSignal, f);
}
The first option simply forwards any argument to the connect
, the second uses polymorphic function pointer from C++11 standard library. It's template argument must correspond to the signature of the signal. Qt signals are void, the /ArgumentTypes.../ need to be replaced by the list of arguments of the function. So if the signal is declared as
void someSignal(int, QString);
the function will be
std::function<void(int, QString)>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With