3

I have a list of String and for each of those I want to call an arbitrary function with different required parameters.

Example:

void method1(QString name, int foo1){}
void method2(QString name, int foo2, bool flag(){}

QStringList list;
list << "ELEM1" << "ELEM2";

And now I want a function to which I can pass any function and its called with given values for each element in list

void callForAll((MyClass::*pt2ConstMember)(QString,X,X)){
    foreach(QString element, list){
        (*m_class.*pt2ConstMember)(element,X,X);
    }
}

callForAll(&MyClass::method1, 4);
callForAll(&MyClass::method2, 6, false)

At its core it seems like I want to do something like this: C++: Function pointer to functions with variable number of arguments or am I going the wrong way with this`?

To make things even more complicated the callForAll function should not be called directly but using signal/slots in Qt. So I would need signal with variadic parameters and the function pointer:

In sender class: Signal:

template<typename F, typename ...PP >
void sigForAll(F f, PP&& ... pp);

Usage:

emit sigForAll(&Receiver::method1, 5, true)

In receiver class:

 template<typename F, typename ...PP >
 void ForAll(F f, PP&& ... pp);

In third class containing member instances of sender and receiver class:

 connect(m_sender, SIGNAL(sigForAll(F f, PP&& ... pp)), m_receiver, SLOT(ForAll(F f, PP&& ... pp)))
Curunir
  • 1,186
  • 2
  • 13
  • 30
  • This can be done with variadic templates and ````std::any```` as container and using a templated ````std::any_cast````. Or with ````std::function```` and ````std::bind````. Or with lambdas. – A M Aug 12 '19 at 09:12

1 Answers1

3

You can use a lambda. It will get optimized much better than a pointer-to-member solution:

template <typename F>
void callForAll(F const& f) {
    foreach(QString element, list) {
        f(element);
    }
}

callForAll([&m_class](QString const& s){ m_class.method1(s, 4); });
callForAll([&m_class](QString const& s){ m_class.method2(s, 6, false); });
rustyx
  • 80,671
  • 25
  • 200
  • 267