Since you apparently need to call a function by name on some "untyped" object (void*
) while passing in a number of arguments that differ by function, you need some kind of multiple-dispatch. A possible solution is:
#include <string>
#include <iostream>
#include <stdexcept>
#include <functional>
#include <utility>
#include <map>
template <typename Subj>
using FunctionMap = std::map<std::string, std::function<void (Subj&, const std::string&)>>;
class AbstractBaseSubject {
public:
virtual void invoke (const std::string& fName, const std::string& arg) = 0;
};
template <typename Class>
class BaseSubject : public AbstractBaseSubject {
public:
virtual void invoke (const std::string& fName, const std::string& arg) {
const FunctionMap<Class>& m = Class::functionMap;
auto iter = m.find (fName);
if (iter == m.end ())
throw std::invalid_argument ("Unknown function \"" + fName + "\"");
iter->second (*static_cast<Class*> (this), arg);
}
};
class Cat : public BaseSubject<Cat> {
public:
Cat (const std::string& name) : name(name) {}
void meow (const std::string& arg) {
std::cout << "Cat(" << name << "): meow (" << arg << ")\n";
}
static const FunctionMap<Cat> functionMap;
private:
std::string name;
};
const FunctionMap<Cat> Cat::functionMap = {
{ "meow", [] (Cat& cat, const std::string& arg) { cat.meow (arg); } }
};
class Dog : public BaseSubject<Dog> {
public:
Dog (int age) : age(age) {}
void bark (float arg) {
std::cout << "Dog(" << age << "): bark (" << arg << ")\n";
}
static const FunctionMap<Dog> functionMap;
private:
int age;
};
const FunctionMap<Dog> Dog::functionMap = {
{ "bark", [] (Dog& dog, const std::string& arg) { dog.bark (std::stof (arg)); }}
};
int main () {
Cat cat ("Mr. Snuggles");
Dog dog (7);
AbstractBaseSubject& abstractDog = dog; // Just to demonstrate that the calls work from the base class.
AbstractBaseSubject& abstractCat = cat;
abstractCat.invoke ("meow", "Please feed me");
abstractDog.invoke ("bark", "3.14");
try {
abstractCat.invoke ("bark", "3.14");
} catch (const std::invalid_argument& ex) {
std::cerr << ex.what () << std::endl;
}
try {
abstractCat.invoke ("quack", "3.14");
} catch (const std::invalid_argument& ex) {
std::cerr << ex.what () << std::endl;
}
try {
abstractDog.invoke ("bark", "This is not a number");
} catch (const std::invalid_argument& ex) {
std::cerr << ex.what () << std::endl;
}
}
Here, all classes with functions to be called this way need to derive from BaseSubject
(which is a CRTP). These classes (here: Cat
and Dog
, let's call them "subjects") have different functions with different arguments (bark
and meow
- of course more than one function per subject is possible). Each subject has its own map
of string-to-function. These functions are not function pointers, but std::function<void (SubjectType&,const std::string&)>
instances. Each of those should call the respective member function of the object, passing in the needed arguments. The arguments need to come from some kind of generic data representation - here, I chose a simple std::string
. It might be a JSON or XML object depending on where your data comes from. The std::function
instances need to deserialize the data and pass it as arguments. The map
is created as a static
variable in each subject class, where the std::function
instances are populated with lambdas. The BaseSubject
class looks up the function
instance and calls it. Since the subject class should always directly derive from BaseSubject<Subject>
, pointers of type BaseSubject<Subject>*
may be directly and safely cast to Subject*
.
Note that there is no unsafe cast at all - it is all handled by virtual functions. Therefore, this should be perfectly portable. Having one map
per subject class is typing-intensive, but allows you to have identically-named functions in different classes. Since some kind of data-unpacking for each function individually is necessary anyways, we have individual unpacking-lambdas inside the map
.
If a function's arguments are just the abstract data structure, i.e. const std::string&
, we could leave the lambdas out and just do:
const FunctionMap<Cat> Cat::functionMap = {
{ "meow", &Cat::meow }
};
Which works by way of std::function
s magic (passing this
via the 1st argument), which, in contrast to function pointers, is well-defined and allowed. This would be particularly useful if all functions have the same signature. In fact, we could then even leave out the std::function
and plug in Jarod42's suggestion.
PS: Just for fun, here's an example where casting a member-function-pointer to an function-pointer fails:
#include <iostream>
struct A {
char x;
A () : x('A') {}
void foo () {
std::cout << "A::foo() x=" << x << std::endl;
}
};
struct B {
char x;
B () : x('B') {}
void foo () {
std::cout << "B::foo() x=" << x << std::endl;
}
};
struct X : A, B {
};
int main () {
void (B::*memPtr) () = &B::foo;
void (*funPtr) (X*) = reinterpret_cast<void (*)(X*)> (memPtr); // Illegal!
X x;
(x.*memPtr) ();
funPtr (&x);
}
On my machine, this prints:
B::foo() x=B
B::foo() x=A
The B
class shouldn't be able to print "x=A"! This happens because member-function pointers carry an extra offset that is added to this
before the call, in case multiple inheritance comes into play. Casting loses this offset. So, when calling the casted function pointer, this
automatically refers to the first base object, while B
is the second, printing the wrong value.
PPS: For even more fun:
If we plug in Jarod42's suggestion:
template <typename C, void (C::*M)(), typename Obj>
void AsFunc (Obj* p) {
(p->*M)();
}
int main () {
void (*funPtr) (X*) = AsFunc<B, &B::foo, X>;
X x;
funPtr (&x);
}
the program correctly prints:
B::foo() x=B
If we look at the disassembly of AsFunc
, we see:
c90 <void AsFunc<B, &B::foo, X>(X*)>:
c90: 48 83 c7 01 add $0x1,%rdi
c94: e9 07 ff ff ff jmpq ba0 <B::foo()>
The compiler automatically generated code that adds 1
to the this
pointer, such that B::foo
is called with this
pointing to the B
base class of X
. To make this happen in the AsFunc
function (opposed to buried within main
), I introduced the Obj
template parameter which lets the p
argument be of the derived type X
such that AsFunc
has to do the adding.
#define
for type aliases. Usetypedef
orusing
, e.g.using GENERIC_FUNC_TYPE = void(*)(void);
.which is why they are all cast to the same signature void(*)(void)
this is just strange. All this casting can and warning can go away if the design was good. Looks strange why the designers didn't wrap the pointers insidestd::function
?myStoredFunction = std::function<void(void*)>([](void*p) { (reinterpret_cast<MyClass*>(p)->*myMemberFunc)(); })
. There is a lot of undefined behavior flying in your code. For you current code I would create a functionvoid call_memberFunc_from_myClass(void*)
that would just exactly that. Do you manipulate thevoid *
argument passed to the functions?