这段代码符合标准吗?
#include <stdio.h>
#include <cstdio>
int main() {
FILE *f1 = 0;
std::FILE *f2 = f1;
}
解释:标准说[headers]:
[...] the contents of each header
cname
shall be the same as that of the corresponding headername.h
[...] as if by inclusion. In the C++ standard library, however, the declarations [...] are within namespace scope (3.3.6) of the namespacestd
. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespacestd
by explicit using-declarations (7.3.3).
因此,如果它们不是通过显式 using 声明注入(inject)的,它们可能是不同类型吗?我不认为“as if by inclusion”这个短语是决定性的,因为文本的另一半显然与此要求相矛盾,要求名称在 std
命名空间内。
最佳答案
是的,符合标准:FILE*
在 stdio.h
中声明, std::FILE*
在 cstdio
,并且由于您引用的段落,两者相同。
(唯一未指定的是,如果您只包括<cstdio>
,您是否在全局命名空间中也有相同的FILE*
。)
更新:我相信类型实际上是一样的,并且每个类型只声明一次,然后通过using
注入(inject)到另一个命名空间中。声明。唯一未指定的是哪个先出现。对应的对立标准引述为D.5(2):
Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).
基本上,这意味着可能有两种实现方式:
“C 先来”:
// foo.h
struct Gizmo { /* ... */ };
// cfoo
#include "foo.h"
namespace std { using ::Gizmo; }
“具有 C 兼容性的 C++:
// cfoo
namespace std
{
struct Gizmo { /* ... */ };
}
// foo.h
#include <cfoo>
using std::Gizmo;
关于c++ - `cname` 和 `name.h` 中的类型可以是不同的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10466096/