C++,用 lambda 实现 typedef? [英] C++, Fulfilling typedef with lambda?

查看:61
本文介绍了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 参数,并且像 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?

推荐答案

我错过了什么?

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_attachInterrupt1,那么我建议你允许它接受任何(类型擦除的)函子.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天全站免登陆