c++ - 为什么不能使用函数的 typedef 来定义函数?

标签 c++ typedef function-declaration

来自 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 declared int, since the argument is known to be passed as an int 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/17848983/

相关文章:

c++ - C++ 中 {} 和 {0} 的大括号初始化区别

C 类型定义冲突

c - 我无法理解这个简单代码的意义

Swift - 在带有可选参数的泛型函数中将 Nil 作为参数

c++ - 使用 UNC 路径读取/写入文件 - 在 C++ 中

c++ - 使用 C++ 的分支模拟器

c++ - 如何获取存储在 std::function 中的 c 风格函数的地址?

c++ - 如何在模板函数中使用 typedef?

c - 函数声明与原型(prototype)的替代 (K&R) C 语法

c - 警告 : conflicting types error