I'm trying to have method void run( string method )
which would run method in that class. For example:
class Foo {
public:
void run( string method ) {
// this method calls method *method* from this class
}
void bar() {
printf( "Function bar\n" );
}
void foo2() {
printf( "Function foo2\n" );
}
}
Foo foo;
int main( void ) {
foo.run( "bar" );
foo.run( "foo2" );
}
this would print:
Function bar
Function foo2
Thanks! :)
You can create an std::map
which maps strings to member function pointers, as long as all the functions you want to call have the same signature.
The map would be declared like:
std::map<std::string, void(Foo::*)()> function_map;
As others have pointed out, C++ doesn't do this kind of reflection out of the box (and odds are that it's probably not what you want to be doing.)
But I'll mention that there do exist some preprocessors out there which implement this functionality for a subset of class types and methods. Qt's moc is an example of this, and it's part of the signal/slot mechanics. Notice method()
and methodCount()
on the QMetaObject ...
The way Qt does this is by injecting a tool into your build process that makes tables and compiles them in with the rest of your code. It's all stuff you could have written by hand--not a language feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With