如何动态执行具有任意参数类型的函数指针?

How do I dynamically execute function pointers having arbitrary argument types?

我有几个具有不同类型参数的函数:

static void fn1(int* x, int* y);
static void fn2(int* x, int* y, int* z);
static void fn3(char* x, double y);
...

我想创建一个新函数,它接收函数指针集合、参数值集合,并使用正确的参数值按顺序执行集合中的每个函数:

static void executeAlgorithm(
    vector<FN_PTR_TYPE> functionToExecute,
    map<FN_PTR_TYPE, FN_ARG_COLLECTION> args)
{
    // for each function in 'functionToExecute',
    // get the appropriate arguments, and call the
    // function using those arguments
}

实现此行为的最简洁方法是什么?

这是基于@KerrekSB 在评论中建议的非常简单的解决方案。您基本上 std::bind 一个函数及其参数,并且由于您不必再传递参数,您的函数变得统一 std::function<void()> 这很容易存储在容器中:

#include <iostream>
#include <vector>
#include <functional>

static void fn1(int x, int y)
{
    std::cout << x << " " << y << std::endl;
}

static void fn2(int x, int *y, double z)
{
    std::cout << x << " " << *y << " " << z << std::endl;
}

static void fn3(const char* x, bool y)
{
    std::cout << x << " " << std::boolalpha << y << std::endl;
}

int main()
{
    std::vector<std::function<void()>> binds;
    int i = 20;

    binds.push_back(std::bind(&fn1, 1, 2));
    binds.push_back(std::bind(&fn1, 3, 4));
    binds.push_back(std::bind(&fn2, 1, &i, 3.99999));
    binds.push_back(std::bind(&fn2, 3, &i, 0.8971233921));
    binds.push_back(std::bind(&fn3, "test1", true));
    binds.push_back(std::bind(&fn3, "test2", false));

    for (auto fn : binds) fn();
}

演示:https://ideone.com/JtCPsj

1 2
3 4
1 20 3.99999
3 20 0.897123
test1 true
test2 false