是否可以将 typedef 用于函数定义?
Is it possible to use a typedef for function DEFINITION?
我经常使用 typedef
s 作为类型和函数 声明。
问题是:是否可以定义具有先前声明的类型(即:签名)的函数?
我的意思是:鉴于众所周知的声明:
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 标准甚至明确指出,它有意禁止 footnote 162 mentioned in 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) { /*...*/ }
我经常使用 typedef
s 作为类型和函数 声明。
问题是:是否可以定义具有先前声明的类型(即:签名)的函数?
我的意思是:鉴于众所周知的声明:
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 标准甚至明确指出,它有意禁止 footnote 162 mentioned in 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) { /*...*/ }