根据ISO / IEC 14882:2011(E)第8.3.5.11条:
A typedef of function type may be used to declare a function but shall not be used to define a function
标准继续给出此示例:
typedef void F();
F fv; // OK: equivalent to void fv();
F fv { } // ill-formed
void fv() { } // OK: definition of fv
是什么激发了这个规则?似乎限制了函数typedef的潜在表达用处。
最佳答案
尽管这个问题是关于C++的,但是由于C++继承了C的typedef
和函数指针,因此在这里可以使用C中相同问题的解释。对C有一个正式的解释。
Rationale for International Standard - Programming Languages C §6.9.1 Function definitions
An argument list must be explicitly present in the declarator; it cannot be inherited from a
typedef
(see §6.7.5.3). That is to say, given the definition:typedef int p(int q, int r);
the following fragment is invalid:
p funk // weird { return q + r ; }
Some current implementations rewrite the type of, for instance, a
char
parameter as if it were declaredint
, since the argument is known to be passed as anint
in the absence of a prototype. The Standard requires, however, that the received argument be converted as if by assignment upon function entry. Type rewriting is thus no longer permissible.
关于c++ - 为什么不能使用函数的typedef来定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62606419/