c++ - 在 C++ (Arduino) 中将带有参数的函数作为参数传递
问题描述
我想为我的班级编写一种包装函数......我真的不知道该怎么做!
看,我想要一个,比如说,run()
函数,接受一个函数作为参数,这很容易。用法类似于
void f() { }
void run(int (*func)) {
//whatever code
func();
//whatever code
}
run(f);
那应该只是运行该f()
功能,对吗?
但是如果f()
需要参数呢?假设它被声明为f(int i, int j)
,我将继续重写run()
函数以分别接受这些int
s,并将它们传递给f()
函数。
但我希望能够将 Any 函数传递给run()
,无论参数有多少,或者它们是什么类型。意思是,最后,我希望得到类似于我所期望的假设的用法
void f() {int i, int j}
void v() {char* a, int size, int position}
void run(int (*func)) {
//whatever code
func();
//whatever code
}
run(f(1, 2));
run(v(array, 1, 2));
去做。我知道这看起来很愚蠢,但我想我已经明白了。
我该怎么做?
请记住,这是 arduino-c++,所以它可能缺少一些东西,但我相信有一些库可以弥补这一点......
解决方案
如果您有权访问,std::function
那么您可以使用它:
void run(std::function<void()> fn) {
// Use fn() to call the proxied function:
fn();
}
您可以使用 lambda 调用此函数:
run([]() { f(1, 2); });
Lambda 甚至可以从其封闭范围中捕获值:
int a = 1;
int b = 2;
run([a, b]() { f(a, b); });
如果你没有,std::function
但你可以使用 lambdas,你可以制作run
一个模板函数:
template <typename T>
void run(T const & fn) {
fn();
}
推荐阅读
- reactjs - 如何刷新 Table 组件 onChange 事件
- javascript - 空jQuery时更改div的属性
- google-app-engine - 谷歌负载均衡器到 Cloud Run 给出 404
- windows - For 循环运行两次,但仅针对第一个文件
- excel - 锁定依赖于其他单元格的单元格
- sql - SQL解析ORACLE 将行转换为列
- sql-server - Automapper ProjectTo<> 不适用于 Count()
- javascript - 如何在 EXT JS 中的分段按钮上应用样式
- java - 如何在 MacOS 上使用 Java 进行 Touch ID 身份验证
- php - 在引导卡中获取信息