[英]Is it possible to use a typedef for function DEFINITION?
I am routinely using typedef
s for type and function declaration .我经常使用
typedef
进行类型和函数声明。
Question is: is it possible to define a function having a previously declared type (ie: signature)?问题是:是否可以定义具有先前声明的类型(即:签名)的函数?
I mean: given the well known declaration:我的意思是:鉴于众所周知的声明:
void (*signal(int sig, void (*func)(int)))(int);
or, better, it's (clearer) equivalent:或者,更好的是,它是(更清晰的)等价的:
typedef void SigCatcher(int);
SigCatcher *signal(int sig, SigCatcher *func);
how is it possible to define a SigCatcher
function?如何定义
SigCatcher
函数?
of course I can define:我当然可以定义:
void my_sig_catcher(int sig, SigCatcher *func) {
...
}
but that doesn't make evident this is really a SigCatcher
.但这并不能说明这真的是一个
SigCatcher
。 What I would like is something like:我想要的是这样的:
SigCatcher my_sig_catcher {
...
}
but this is not a valid construct.但这不是一个有效的构造。
Is there some (not too contrived) way to achieve this?有没有一些(不太人为的)方法来实现这一目标?
It's not possible.这是不可能的。 It's not possible, because the language grammar disallows it.
这是不可能的,因为语言语法不允许这样做。 The C standard even explicitly states, that it has the intent of disallowing such function definitions in footnote 162 mentioned in 6.9.1p2 .
C 标准甚至明确指出,它的意图是禁止6.9.1p2 中提到的脚注 162中的此类函数定义。 I copied the footnote below in the hopes it will clears things up:
我复制了下面的脚注,希望它能解决问题:
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
What's interesting, it's allowed for function declarations.有趣的是,它允许用于函数声明。 So the following is possible:
所以以下是可能的:
SigCatcher my_sig_catcher;
But the definition has to be:但定义必须是:
void SigCatcher(int some_name) { /*...*/ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.