是否可以使用回调类型定义来定义函数? [英] Is it possible to define a function using a callback type definition?

查看:61
本文介绍了是否可以使用回调类型定义来定义函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣使用预定义的回调类型定义函数。

I'm interested in defining a function using a predefined callback type.

假设我已定义了回调类型:

Let's assume I have defined callback type:

typedef BOOL (*is_trigger_required_cb)(void);

现在,我想使用上述类型声明和定义一个函数。

Now I would like to declare and define a function using the above type.

我想做类似的事情:

is_trigger_required_cb my_func { /* function implementation which accepts void and returns BOOL */ }

由于以下原因而无法编译:

This won't compile due to:


错误:预期为';'在顶级声明符之后

error: expected ';' after top level declarator

到我的理解是不可能的,因为编译器仅将回调类型称为类型安全的函数指针,而不能用于函数定义。万一回调类型发生变化,则会中断编译,从而保持类型安全。

To my understanding it is not possible since the compiler refers to the callback type merely as type-safe function pointer and cannot be used for function definition. In case there's a change of callback type, it would break the compilation thus type safety is maintained.

推荐答案

如果定义 function 类型,则可以将其近似。

You cam approximate it if you define function types.

typedef BOOL is_trigger_required_cb(void);

这将使回调成为显式指针(我认为是加号)

that will make the callback be an explicit pointer (something I consider a plus)

is_trigger_required_cb *cb;

,并且至少允许您使用以下类型的声明函数:

and will allow you to at least declare functions with that type:

is_trigger_required_cb my_func;
BOOL my_func (void) {
  // Do stuff
}

在定义时,您仍然需要重复完整的原型,这是无法避免的,因为语法会迫使您动手。但是至少您可以进行类型检查,因为声明必须与原型函数的定义相匹配。

You still need to repeat the full prototype at the point of definition, there is no getting around that, because the grammar forces your hand. But at least you get the type checking you were after, since the declaration must match the definition of a prototyped function.

但是,这似乎很不可思议,因为这不是必需的。通常会看到。我建议您权衡一下它的优点和需要解释的地方。

It may appear arcane however, since this is not something one normally sees. I suggest you weigh the merits of it against the need to explain it.

这篇关于是否可以使用回调类型定义来定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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