可以在函数定义中使用函数原型 typedef 吗? [英] Can a function prototype typedef be used in function definitions?
问题描述
我有一系列具有相同原型的函数,比如说
I have a series of functions with the same prototype, say
int func1(int a, int b) {
// ...
}
int func2(int a, int b) {
// ...
}
// ...
现在,我想简化它们的定义和声明.我当然可以使用这样的宏:
Now, I want to simplify their definition and declaration. Of course I could use a macro like that:
#define SP_FUNC(name) int name(int a, int b)
但我想将其保留在 C 中,因此我尝试为此使用存储说明符 typedef
:
But I'd like to keep it in C, so I tried to use the storage specifier typedef
for this:
typedef int SpFunc(int a, int b);
这似乎适用于声明:
SpFunc func1; // compiles
但不是定义:
SpFunc func1 {
// ...
}
这给了我以下错误:
error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
有没有办法正确地做到这一点还是不可能?根据我对 C 的理解,这应该有效,但它没有.为什么?
Is there a way to do this correctly or is it impossible? To my understanding of C this should work, but it doesn't. Why?
注意,gcc 理解我想要做什么,因为,如果我写
Note, gcc understands what I am trying to do, because, if I write
SpFunc func1 = { /* ... */ }
它告诉我
error: function 'func1' is initialized like a variable
这意味着 gcc 理解 SpFunc 是一个函数类型.
Which means that gcc understands that SpFunc is a function type.
推荐答案
不能使用函数类型的 typedef 定义函数.这是明确禁止的 - 请参阅 6.9.1/2 和相关的脚注:
You cannot define a function using a typedef for a function type. It's explicitly forbidden - refer to 6.9.1/2 and the associated footnote:
在函数定义中声明的标识符(即函数的名称)应具有函数类型,如函数定义的声明符部分所指定.
The identifier declared in a function definition (which is the name of the function) shall have a function type, as specified by the declarator portion of the function definition.
目的是不能从 typedef 继承函数定义中的类型类别:
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
这篇关于可以在函数定义中使用函数原型 typedef 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!