繁体   English   中英

是否可以将 typedef 用于函数定义?

[英]Is it possible to use a typedef for function DEFINITION?

我经常使用typedef进行类型和函数声明

问题是:是否可以定义具有先前声明的类型(即:签名)的函数?

我的意思是:鉴于众所周知的声明:

void (*signal(int sig, void (*func)(int)))(int);

或者,更好的是,它是(更清晰的)等价的:

typedef void SigCatcher(int);
SigCatcher *signal(int sig, SigCatcher *func);

如何定义SigCatcher函数?

我当然可以定义:

void my_sig_catcher(int sig, SigCatcher *func) {
    ...
}

但这并不能说明这真的是一个SigCatcher 我想要的是这样的:

SigCatcher my_sig_catcher {
    ...
}

但这不是一个有效的构造。

有没有一些(不太人为的)方法来实现这一目标?

这是不可能的。 这是不可能的,因为语言语法不允许这样做。 C 标准甚至明确指出,它的意图是禁止6.9.1p2 中提到的脚注 162中的此类函数定义。 我复制了下面的脚注,希望它能解决问题:

162) The intent is that the type category in a function definition cannot be inherited from a typedef: 

      typedef int F(void);                          //   type F is ''function with no parameters
                                                    //                  returning int''
      F f, g;                                       //   f and g both have type compatible with F
      F f { /* ... */ }                             //   WRONG: syntax/constraint error
      F g() { /* ... */ }                           //   WRONG: declares that g returns a function
      int f(void) { /* ... */ }                     //   RIGHT: f has type compatible with F
      int g() { /* ... */ }                         //   RIGHT: g has type compatible with F
      F *e(void) { /* ... */ }                      //   e returns a pointer to a function
      F *((e))(void) { /* ... */ }                  //   same: parentheses irrelevant
      int (*fp)(void);                              //   fp points to a function that has type F
      F *Fp;                                        //   Fp points to a function that has type F

有趣的是,它允许用于函数声明。 所以以下是可能的:

SigCatcher my_sig_catcher;

但定义必须是:

void SigCatcher(int some_name) { /*...*/ }

暂无
暂无

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

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