I'm trying to pass any generic function as an argument in a C++ function. As an extra layer of fun, the function is going to reside in its own separate class. In this particular case, they will all take no arguments and return void
. This includes members of any generic class.
My current code reads like:
class functionsFedHere {
public:
void (*callback)();
functionsFedHere(void(*)());
}
functionsFedHere::functionsFedHere (void(*callbackFunction)()) {
callback = callbackFunction;
}
void fn1() { cout<<"Fn1"<<endl; }
class myClass {
public:
int i;
void fn2() { cout<<i<<endl; }
}
class myOtherClass {
public:
string j;
void fn3() { cout<<j<<endl; }
}
int main() {
// Initialise some objects
myClass b;
b.i = 2;
myOtherClass c;
c.j = "some text";
// Works fine with non-member functions
functionsFedHere objectA(fn1);
objectA.callback();
// Doesn't work with member functions
functionsFedHere objectB(b.fn2);
functionsFedHere objectC(c.fn3);
}
I've seen solutions like a forwarding function, or boost::bind, but as far as I can tell, I don't think these solutions will fit?
It's also worth noting that eventually I'd like to pass member functions by way of an array of pointers. For example, if myPointer[]
is an array of pointers to objects of class myClass
, then it would be nice to be able to write something like:
functionsFedHere objectD(myPointer[0]->fn2);
EDIT: Apparently I wasn't clear enough. This answer is not an appropriate answer, because I'm looking to pass both member and non-member functions as arguments (whereas the suggested answer is setting up a member pointer to a function that is a member of the same class).
I don't think that the forward function example will work, because the forwarding function assumes a single class type, where I'd like to pass an object of generic class.
boost::bind
could well be the answer; I'm just unfamiliar with it. Can anyone point me towards some newbie-friendly reading material?
EDIT 2: Sorry, forgot to mention I'm programming on a device that is pre-C++11.