简体   繁体   English

编译时动态函数调用

[英]Compile time dynamic function call

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! 谢谢!

This is Reflection and is not available natively in C++ 这是Reflection在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. 如果methodName的可能值有限,则可以构建一个Lookup表,该表根据methodName调用相应的函数,但不能使用此系统调用任意函数。

This could either be a std::map as @PaperBirdMaster suggests or a giant set of if-else checks. 这可以是@PaperBirdMaster建议的std :: map,也可以是一组if-else检查。 But this is not true Reflection, just a crude illusion of the same. 但这不是真实的反思,只是一种粗暴的错觉。

You could create a Macro: 你可以创建一个宏:

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

in main function: 在主要功能:

CallMethod(foo,"test");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM