c++ - 具有可变参数的映射函数并通过字符串调用 c++

标签 c++ c++11

我想知道如何映射具有可变参数的函数,返回 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/

相关文章:

c++ - Visual Studio for C++ __cplusplus 支持的语言显示为 C++98

c++ - 将目录传递给 g++ 以包含文件的正确标志

c++ - std::call_once() 在 callable 抛出第一次调用后在第二次调用时挂起

c++ - 在向 std::unordered_map 插入元素时避免不必要的构造函数调用?

c++ - 用树莓派运行 C++ 文件

c++ - 是否有可以在 Win32 和 MacOSX 系统上使用的跨平台 unicode 字符串类?

c# - 我如何在 C# 函数中转换 C++ 函数

c++ - 使用 nonfree/feature2d.hpp 的 OpenCV 编译错误

c++ - 如果选择上面的 if 语句,else-is 会解析吗?

c++ - 连接元组作为类型