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

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

本文关键字:参数 任意 类型 指针 函数 何动态 动态 执行      更新时间:2023-10-16

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

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