c++ - `cname` 和 `name.h` 中的类型可以是不同的类型吗?

标签 c++ standards-compliance language-lawyer standard-library

这段代码符合标准吗?

#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 header name.h [...] as if by inclusion. In the C++ standard library, however, the declarations [...] are within namespace scope (3.3.6) of the namespace std. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std 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/

相关文章:

c++ - 如何在 C++ 中使用 Poco 连接安全的 websocket

c++ - Visual Studio C++ 编译器中的错误?

c++ - 为什么由 const 限定的变体成员组成的 union 会导致没有默认的默认构造函数?

c - C99 的支持有多普遍?

c++ - 字节真的是最小可寻址单位吗?

c++ - 是否允许枚举具有未列出的值?

c++ - D3D11 不知从哪里增加了引用计数?

c++ - 未调用 boost spirit 语义 Action

c++ - 错误 QApplication : no such file or directory

c++ - 是否有任何编译器忽略有关默认内联函数的 C++ 标准?