首页 > 解决方案 > 在 C++ (Arduino) 中将带有参数的函数作为参数传递

问题描述

我想为我的班级编写一种包装函数......我真的不知道该怎么做!

看,我想要一个,比如说,run()函数,接受一个函数作为参数,这很容易。用法类似于

void f() { }
void run(int (*func)) { 
//whatever code
func();
//whatever code
}
run(f);

那应该只是运行该f()功能,对吗?

但是如果f()需要参数呢?假设它被声明为f(int i, int j),我将继续重写run()函数以分别接受这些ints,并将它们传递给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++,所以它可能缺少一些东西,但我相信有一些库可以弥补这一点......

标签: c++pointersarduinoargumentsarduino-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();
}

推荐阅读