gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:07:00 24 4
gpt4 key购买 nike

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

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

关于c++ - 如何动态执行具有任意参数类型的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49390595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com