Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ call arbitrary function for each element

Tags:

c++

pointers

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)))
like image 225
Curunir Avatar asked Mar 20 '26 02:03

Curunir


1 Answers

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); });
like image 109
rustyx Avatar answered Mar 25 '26 03:03

rustyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!