我想知道如何映射具有可变参数的函数,返回 int 类型并通过字符串调用它..
举个例子……
int func1(int a, int b);
int func2(int a1, int b1 , int* c1);
int func3(char* dummy);
int func4(double x, long y, int z, char** table);
int func5(double d1, double b1);
int func6(int* p, double* q, int i);
我只需要一个普通的函数叫做
int CallFunction("funcname", param1, param2, ...);
例如
CallFunction("func1", 10, 20); /* calling function func1 and return func1 result*/
我知道如何使用具有常量参数的函数指针来映射函数,但可变参数似乎很复杂.. 谁能告诉我如何去做。
我什至探索了 Variadic 模板..但似乎使用字符串调用函数很复杂..
最佳答案
我遇到了完全相同的问题。
用这个解决方案解决了它:
#include <iostream>
#include <map>
#include <string>
int func0(int x)
{
std::cout << x << std::endl;
}
int func1(int x, int y)
{
std::cout << (x + y) << std::endl;
}
template <class... Args>
struct MapHolder{
static std::map<std::string, int (*)(Args...)> CallbackMap;
};
template <class... Args>
std::map<std::string, int (*)(Args...)> MapHolder<Args...>::CallbackMap;
class Callback {
public:
template <class ...Args>
void RegisterFunction(std::string name, int (*func)(Args...)) {
MapHolder<Args...>::CallbackMap[name] = func;
}
template <class ...Args>
int ExecuteFunction(std::string name, Args &&... args) {
return MapHolder<Args...>::CallbackMap[name](std::forward<Args>(args)...);
};
};
int main(int argc, char *argv[])
{
Callback cb;
cb.RegisterFunction("func0", &func0);
cb.RegisterFunction("func1", &func1);
cb.ExecuteFunction("func0", 42);
cb.ExecuteFunction("func1", 42, 42);
return 0;
}
此代码段基于此 answer .我只使用其他类/函数名称。
关于c++ - 具有可变参数的映射函数并通过字符串调用 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27670222/