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

How to get function pointer from many functions and pass args to it?

我定义了很多函数如下,所有return一个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?
         
    }
}

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

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

受到评论的启发:

采用 some_struct_t data, std::vector<std::string> field_names 的包装器。假设一个

template <typename T>
T get_from_data(some_struct_t, std::string);

你有一个函数类型

using func_t = std::function<int(const some_struct_t &, const std::vector<std::string>&)>;

您可以通过

从函数实例化
template <typename... Args, size_t... Is>
auto wrap_impl(int(*func)(Args...), std::index_sequence<Is...>)
{
    return [func](const some_struct_t & data, const std::vector<std::string>& field_names)
        { return func(get_from_data<Args>(data, field_names.at(Is))...); };
}

template <typename... Args>
func_t wrap(int(*func)(Args...))
{
    return wrap_impl(func, std::index_sequence_for<Args...>{});
}

然后你可以有一个

std::map<std::string, func_t> functions;