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

时间:2018-03-20 17:26:31

标签: c++ function function-pointers

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

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
}

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

1 个答案:

答案 0 :(得分:2)

这是基于@KerrekSB在评论中建议的非常简单的解决方案。你基本上std::bind一个函数及其args,并且由于你不必再传递args,你的函数变得统一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