编译时动态函数调用



不确定标题是否突出了我的目标。

我可以在编译时动态调用方法吗?例如:

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");

谢谢!

您可以创建一个宏:

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

在主函数中:

CallMethod(foo,"test");
这是

反射,在C++中本身不可用

如果methodName的可能值数量有限,则可以构建一个查找表,该表根据methodName调用相应的函数,但不能使用此系统调用任意函数。

这可以是@PaperBirdMaster建议的 std::map,也可以是一组巨大的if-else检查。但这不是真正的反思,只是一种粗暴的幻觉。

最新更新