简体   繁体   English

在 C++ (Arduino) 中将 function 和 arguments 作为参数传递

[英]Passing a function with arguments as an argument in C++ (Arduino)

I'd like to write a sort-of wrapper function for my class... And i really dont know how to do that!我想为我的 class 编写一种包装器 function ......我真的不知道该怎么做!

See, i want a, say, run() , function, to accept a function as an argument, thats the easy part.看,我想要一个run() , function 来接受 function 作为参数,这很容易。 The usage would be something like用法类似于

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

That should just run the f() function, right?那应该只运行f() function,对吧?

But what if f() had required arguments?但是如果f()需要 arguments 怎么办? Say it was declared as f(int i, int j) , i would go along rewriting the run() function to separately accept those int s, and pass them to the f() function.假设它被声明为f(int i, int j) ,我将 go 重写run() function 以分别接受这些int s,并将它们传递给f() ZC1C425268E683894F1AB457A。

But I'd like to be able to pass Any function to run() , no matter how many arguments, or what type they are.但我希望能够将 Any function 传递给run() ,无论有多少 arguments 或它们是什么类型。 Meaning, in the end, i'd like to get usage similar to what i would expect the hypothetical意思是,最后,我希望得到类似于我所期望的假设的用法

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));

to do.去做。 I know it looks dumb, but i think i'm getting my point across.我知道这看起来很愚蠢,但我想我已经明白了。

How would i do that?我该怎么做?

Please remember that this is arduino-c++, so it might lack some stuff, but i do believe there are libraries that could make up for that...请记住,这是 arduino-c++,所以它可能缺少一些东西,但我相信有一些库可以弥补这一点......

If you have access to std::function then you can just use that:如果您可以访问std::function那么您可以使用它:

void run(std::function<void()> fn) {
    // Use fn() to call the proxied function:
    fn();
}

You can invoke this function with a lambda:您可以使用 lambda 调用此 function:

run([]() { f(1, 2); });

Lambdas can even capture values from their enclosing scope: Lambda 甚至可以从其封闭的 scope 中捕获值:

int a = 1;
int b = 2;
run([a, b]() { f(a, b); });

If you don't have std::function but you can use lambdas, you could make run a template function:如果您没有std::function但可以使用 lambda,则可以run模板 function:

template <typename T>
void run(T const & fn) {
    fn();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM