I am working on a piece of core code where a function will be stored within an object and then will be called later when needed. So far I have used function pointers to build a first draft of this:
class caller {
int (*f)();
caller(int (*function)()){
f = function;
}
void timeIsRight(){
f();
}
caller(otherFunction);
This works for calling functions from other areas of the code however I would like to be able to handle passing object members to the caller I.E:
caller(object.aFunction);
Although my compiler is complaining about the above which leads me to believe I am approaching this wrong (I have tried a few other ways of writing the above to no avail.
I have tried moving the caller into the object class:
class object{
...
int myMember(){...}
caller(myMember);
...
}
Although I get the error int(namespace::object::*)() is incompatible with int(*)()
This would tell me that I need to tell the caller where the functions originates.
Now ideally I would like caller to be able to take any function that returns an int
and has no parameters irregardless of where it is located (namespace, class ect)
From my reading so far two possible routes I could go down are:
- Creating Templates
- Use Member Pointers
I am also willing to switch from functions pointers to function objects or lamdas if these would fulfill my needs.
Would any of the above approaches be able to get me the result I want and if so I would greatly appropriate a push in the right direction, as I have found a lot of breadth to my search with little helpful depth.
Thanks all.
Please note I am after a class/namespace agnostic approach, which is my primary design constraint. If these are not possible with function pointers I am happy to move to objects, lamdas to building something else up.
However as I do not know the class at compile time the linked answer will not assist with my problem.