是否可以对函数DEFINITION使用typedef?

问题描述 投票:1回答:1

我通常将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 syntax typedef
1个回答
1
投票

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

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) { /*...*/ }
© www.soinside.com 2019 - 2024. All rights reserved.