在C ++(Arduino)中将带有实参的函数作为实参传递 [英] Passing a function with arguments as an argument in C++ (Arduino)

查看:74
本文介绍了在C ++(Arduino)中将带有实参的函数作为实参传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的课写一个包装函数……而且我真的不知道该怎么做!

I'd like to write a sort-of wrapper function for my class... And i really dont know how to do that!

看,我想让一个 run()函数接受一个函数作为参数,这就是简单的部分.用法类似于

See, i want a, say, run(), function, to accept a function as an argument, thats the easy part. The usage would be something like

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

那应该只运行 f()函数,对吧?

That should just run the f() function, right?

但是,如果 f()具有必需的参数怎么办?假设它被声明为 f(int i,int j),我将继续重写 run()函数以单独接受那些 int s,然后将它们传递给 f()函数.

But what if f() had required arguments? Say it was declared as f(int i, int j), i would go along rewriting the run() function to separately accept those ints, and pass them to the f() function.

但我希望能够将Any函数传递给 run(),无论它们有多少个参数或它们是什么类型.意思是说,最后,我想获得与假设的

But I'd like to be able to pass Any function to run(), no matter how many arguments, or what type they are. 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.

我该怎么做?

请记住,这是arduino-c ++,所以它可能缺少一些东西,但是我确实相信有一些库可以弥补这一点...

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...

推荐答案

如果您可以访问

If you have access to std::function then you can just use that:

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

您可以使用lambda调用此函数:

You can invoke this function with a lambda:

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

Lambda甚至可以从其封闭范围捕获值:

Lambdas can even capture values from their enclosing scope:

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

如果没有 std :: function ,但可以使用lambda,则可以使 run 为模板函数:

If you don't have std::function but you can use lambdas, you could make run a template function:

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

这篇关于在C ++(Arduino)中将带有实参的函数作为实参传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆