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

Now that Qt5 supports connecting signals to lambda functions, I would like to be able to pass the lambda as an argument to another function. I have a function that looks something like this:

void SomeFunc(Functor f)
{
    connect(obj, &MyObject::someSignal, f);
}

      

However, the compiler complains when I do this:

"Functor" has not been declared

      

Change Functor

to QtPrivate::Functor

gives:

QtPrivate::Functor is not a type

      

Basically, all I want to do is pass an argument that QObject::connect

will be available to my function. What type should I use?

+3


source to share


1 answer


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 redirects any argument to connect

, the second uses a polymorphic function pointer from the C ++ 11 standard library. The template argument must match the signal signature. Qt signals are not valid, / ArgumentTypes ... / needs to be replaced with function argument list. Therefore, if the signal is declared as

void someSignal(int, QString);

      

function will be

std::function<void(int, QString)>

      

+7


source







All Articles