繁体   English   中英

C ++中复杂的Typedef

[英]complicated Typedef in C++

据我所知,typedef可用于定义新的自定义类型,例如:

// simple typedef
typedef unsigned long ulong;

// the following two objects have the same type 
unsigned long l1;
ulong l2;

我最近遇到了这个typedef,并且在解读声明中发生的事情时迷失了方向:

typedef int16_t CALL_CONVENTION(* product_init_t)(product_descript_t *const description)

有人可以指导我并解释这是做什么的吗?

编辑:将NEW_TYPE更改为CALL_CONVENTION。 这是一个定义。 谢谢你发现了这一点。

它声明类型product_init_t作为指向函数的指针

  • 取参数product_descript_t *const description ;
  • 返回int16_t ;
  • 使用调用约定CALL_CONVENTION (正如@MM建议,即使它被错误命名)。

PS因为“ 2016年的完整答案应该显示编写这种type-alias的现代方式 ”( @Howard Hinnant ),这里是:

using product_init_t = int16_t (CALL_CONVENTION *)(product_descript_t *const description);

以下是如何理解复杂的typedef:首先看一下取出typedef的行:

int16_t NEW_TYPE (* product_init_t)(product_descript_t *const description);

然后计算出这一行会声明的内容:它是一个名为product_init_t的变量,具有某种类型。

最后,添加typedef意味着它声明product_init_t是该特定类型的别名,而不是该类型的变量。


要计算出上述声明,你可以使用cdecl ,或者你可以使用可能的声明符(指针,数组,函数)从外向内攻击它。

在这种情况下,最外面的特征是右边的参数列表,所以我们怀疑这可能是一个函数声明符。 函数声明符看起来像(粗略地):

returntype    function_name   (parameters_opt)

但请记住,常见的编译器扩展是通过__declspec或其他方式指定函数的附加属性,与返回类型位于同一位置; 或者那里可能有extern "C" ,依此类推。

到目前为止,我们处于(*product_init_t)是一个函数,其中int16_t NEW_TYPE作为返回类型(和可能的declspecs),以及参数列表(product_descript_t *const description)

最后, * product_init_t只是一个指针声明符,因此我们得出结论, product_init_t是指向上述类型函数的指针。

您的评论表明对NEW_TYPE不确定。 它将是之前已经定义的东西(或编译器扩展关键字); 如果你的IDE找不到它的定义,或许用gcc -E预处理代码会有所帮助。

这是#definetypedef用法之间差异的一个有趣例子。

#define FX_TYPE void (*)(int)
typedef void (*stdfx)(int);

void fx_typ(stdfx fx); /* ok */
void fx_def(FX_TYPE fx); /* error */

请看这里

因此,如果有以下情况:

typedef int16_t CALL_CONVENTION(* product_init_t)(product_descript_t *const description)

我们可以使用上面的typedef如下:

void fx_typ(product_init_t fx);

fx是一个指向函数的指针,它将product_descript_t *const description作为参数并返回int16_t

CALL_CONVENTION的使用令人困惑,但是,可以通过空宏来抑制它,如下所示:

#define  CALL_CONVENTION

注意:以上微型没有机身。 在我看来, CALL_CONVENTION只会增加混乱。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM