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

查看:29
本文介绍了在 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() 函数以分别接受那些 ints,并将它们传递给 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...

推荐答案

如果您有权访问 std::function 然后你可以使用它:

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 但你可以使用 lambdas,你可以让 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天全站免登陆