[英]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.