Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Qt type do I need to use to pass a lambda as a function argument?

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?

like image 215
Nathan Osman Avatar asked Feb 05 '13 08:02

Nathan Osman


People also ask

Which is valid type for this lambda function?

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.

How do you pass a lambda function in C++?

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.

Is lambda function a function 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.


1 Answers

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)>
like image 108
Jan Hudec Avatar answered Sep 22 '22 20:09

Jan Hudec