1

There is in Qt such functionality: QMetaObject::invokeMethod(QObject * obj, const char * member, ...), which invokes method from string (member). How can I do the same (or similar)? Thanks)

Matteo Italia
  • 115,256
  • 16
  • 181
  • 279
Lex
  • 161
  • 1
  • 13

2 Answers2

4

You can't do this in pure c++, but you can read about reflection/introspect in c++ in this question

Community
  • 1
  • 1
CAMOBAP
  • 5,011
  • 8
  • 53
  • 84
  • Thanks! That was really useful) – Lex Jan 14 '13 at 16:22
  • @CAMOBAP: Of course you can call methods depending on a `string`. The simplest example being a `map>`. You can even do this for variably long argument lists, including a runtime check for call signature correctness (but it gets a bit ugly). – Sebastian Mach Jan 14 '13 at 17:07
  • Actually I feel the need to give a downvote, because answering such a broad question with simply "you can't" is wrong and it simply isn't true. – Sebastian Mach Jan 14 '13 at 17:20
4

A similar thing can be achieved with a map<std::string, std::function<void()>>:

std::map<std::string, std::function<void()>> funs;
funs["hello world"] = [] () { std::cout << "hello world"; };
funs["hello world"]();

The question is how similar do you want it? How "native" should the call look like?. You can do things like:

void foobar(int, float);

...

    invoke("foobar", 5, 5.f);

but the implementation looks hacky and is non-trivial.

There is a related problem:

You can get pretty far with variadic templates and some template/virtual techniques. With the following codes, you'll be able to do something like:

std::string select_string (bool cond, std::string a, std::string b) {
    return cond ? a : b;
}

int main () {
    Registry reg;
    reg.set ("select_it", select_string);
    reg.invoke ("select_it", "1 John Wayne"));
    reg.invoke ("select_it", "0 John Wayne"));
}

i.e. where the argument list is dissected into a real argument list for a native function call. With variadic templates you can do a lot of things; I am not sure if you should.

Community
  • 1
  • 1
Sebastian Mach
  • 36,158
  • 4
  • 87
  • 126