【问题标题】:Is it possible to use a typedef for function DEFINITION?是否可以对函数 DEFINITION 使用 typedef?
【发布时间】:2019-12-04 22:08:34
【问题描述】:

我经常将typedefs 用于类型和函数声明

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

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

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 {
    ...
}

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

是否有一些(不太做作的)方法来实现这一点?

【问题讨论】:

  • 我会说一个几乎肯定的“不”......但让我们看看我是否错了。
  • 如果允许的话,对于带参数的函数,它仍然无法使用,因为无法将它们命名为在函数体中使用...
  • void my_sig_catcher(int sig, SigCatcher *func)的声明与SigCatcher my_sig_catchervoid my_sig_catcher(int)的声明不兼容,我猜, SigCatcher *func只是一个错字。

标签: c syntax typedef


【解决方案1】:

这是不可能的。这是不可能的,因为语言语法不允许这样做。 C 标准甚至明确指出,它的目的是禁止在 6.9.1p2 中提到的 footnote 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) { /*...*/ }

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2014-01-17
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多