如何从许多函数中获取函数指针并将args传递给它?

问题描述

我有很多定义的函数,如下所示,全部返回一个int

int fn1(int x) {
    return x;
}

int fn2(std::string x,int y,std::string z) {
    // process string x and z
    int x1 = process(x);
    int z1 = process(z);
    return x1 + y + z1;
}

// ... and many more similar functions

由于某些原因,我需要实现一个包装器,以按函数名称调用上述函数,

int wrapper(std::string fn_name,some_struct_t data,std::vector<std::string> field_names) {
    a_fn_ptr_type fn_ptr = nullptr; // <q1>: is this a right way to do?

    // by fn_name,decide which fn to call
    if (fn_name == "fn1") {
        fn_ptr = &fn1;
    }
    if (fn_name == "fn2") {
        fn_ptr = &fn2;
    }
    ...

    // given field_names,get the field from data,pass them to fn_ptr as args
    for (auto field_name: field_names) {
        std::any value = get_from_data(data,field_name,field_type); // field_type will be updated by this call,so that we know the value type.
        
        // <q2>: but how to pass each value as arg to fn_ptr here?
         
    }
}

上面的代码演示了我要实现的目标,我有两个问题(由<q1><q2>指出)。

我不确定代码是否正确,希望从人们那里得到一些建议,谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)