如何动态执行具有任意参数类型的函数指针
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
相关文章:
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 具有任意数量参数的模板函数
- 将任意模板向量作为函数参数C++传递
- C++:任意函数作为函数的参数
- 如何在 C++ 中为任意数量的字符串串联编写可变参数函数
- 使用 std::function 作为具有任意数量参数的数据成员
- 使用模板将任意类型参数传递给 C++ 中的函数
- 使用来自C++的任意数量的参数(在编译时未知)调用 Python 函数
- C++具有模板成员的类,该类使用任意模板参数构造模板成员
- is_invocable使用任意函数参数类型
- 如何动态执行具有任意参数类型的函数指针
- Java函数在C++中具有任意数量的参数
- 使用 lambda 和可变参数模板延迟初始化对象 - 任意传递值
- 在 C++ 中使用 vector 传递任意数量的参数
- 如何为函数参数指定任意模板参数?
- lambda/任意Arity的功能和以捕获为函数参数的功能
- 将具有任意参数和占位符的函数存储在类中,然后再调用它
- 在C++中,是否可以将任意指针作为输入参数
- 使用模板类的任意数量的参数分配
- visual如何在C++中创建一个函数来提供任意数量的参数