C ++,用lambda填充typedef吗? [英] C++, Fulfilling typedef with lambda?

查看:180
本文介绍了C ++,用lambda填充typedef吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能,例如:

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参数,并像tye​​pdef这样返回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_attachInterrupt1, 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无法在进行修改.但我建议那些可能修改功能的人使用.


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屋!

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