2

Not sure the title highlights my goal.

Can I dynamically call a method at compile time ? For example:

int CallMethod(string methodName, string methodArg)
{
    Foo foo;
    return foo.#methodName(methodArg);
}

CallMethod("getValue", "test"); // This would attempt to call on a Foo instance, method getValue with argument "test" -- foo.getValue("test");

Thanks!

codeJack
  • 2,423
  • 5
  • 24
  • 31

2 Answers2

4

This is Reflection and is not available natively in C++

If you have a limited number of possible values for methodName you could build a Lookup table which calls the appropriate function based on methodName but you cannot call arbitrary functions with this system.

This could either be a std::map as @PaperBirdMaster suggests or a giant set of if-else checks. But this is not true Reflection, just a crude illusion of the same.

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • The only approach I can think about to achieve the OP requeriments is to create a map with string and member function pointers... but it isn't reflection at all – PaperBirdMaster Dec 19 '12 at 10:05
  • Is is possible to achieve what I'm trying to do with the help of boost extensions ? Could you give me a reflection example using boost if that is possible ? thanks! – codeJack Dec 19 '12 at 10:06
  • It's not reflection if it's at compile time. – Yochai Timmer Dec 19 '12 at 10:06
  • @YochaiTimmer True if it is a string literal he can try your suggestion, it should work perfectly, I would just enclose it in `{}` though. If he wants to control function name dynamically however.. – Karthik T Dec 19 '12 at 10:08
4

You could create a Macro:

#define CallMethod(methodName, var) { Foo foo; foo.##methodName(var); }

in main function:

CallMethod(foo,"test");
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185