Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a method given only its name?

Tags:

c++

methods

class

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! :)

like image 385
mfolnovich Avatar asked Dec 23 '09 22:12

mfolnovich


2 Answers

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;
like image 58
Charles Salvia Avatar answered Sep 20 '22 03:09

Charles Salvia


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.

like image 24
HostileFork says dont trust SE Avatar answered Sep 23 '22 03:09

HostileFork says dont trust SE