C ++,用lambda填充typedef吗? [英] C++, Fulfilling typedef with lambda?
问题描述
我有一个功能,例如:
typedef void(*timercallback)(void);
void timer1_attachInterrupt(timercallback userFunc);
我希望调用成员方法而不是C样式函数,因此我尝试了以下lambda:
I wish to call a member method rather than a C style function, so I have tried the following lambda:
timer1_attachInterrupt([this](void) -> void { _member_method(); });
但是我收到编译器错误:
However I get the compiler error:
没有合适的转换函数,从"lambda [] void()-> void"转换为 "timercallback"存在
No suitable conversion function from "lambda [] void () -> void" to "timercallback" exists
据我所知,lambda具有像typedef这样的void参数,并像tyepdef这样返回void.我想念什么?
As far as I can see, the lambda has void arguments like the typedef, and returns void like the tyepdef. What am I missing?
推荐答案
我想念什么?
What am I missing?
lambda创建一个闭包对象,因为它需要捕获状态.因此,您不能仅将其传递到需要常规函数指针的位置.
The lambda creates a closure object since it needs to capture state. Therefore you can't just pass it where a regular function pointer is expected.
由于您的API没有为将状态传递给回调做任何准备,因此您将需要使用诸如全局变量之类的令人讨厌的东西.
Since your API doesn't make any provisions for passing state to the callback, you will need to use something unpleasant like global variables.
如果您可以修改timer1_attachInterrupt
1 ,那么我建议您允许它接受任何(类型擦除的)函子. std::function
只是用于完成此任务的实用程序:
If you can modify timer1_attachInterrupt
1, then I suggest you allow it to accept any (type-erased) functor. std::function
is just the utility to accomplish that:
using timercallback = void(void);
void timer1_attachInterrupt(std::function<timercallback> userFunc);
1 很显然,OP无法在 arduino 进行修改.但我建议那些可能修改其功能的人使用.
1It's quite clear the OP can't after the arduino edit. But I leave the suggestion for anyone who may be able to modify their functions.
这篇关于C ++,用lambda填充typedef吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!