c++ - 在带或不带命名空间的 <cstdint> 中使用类型

标签 c++ stl c++11

在 C++11 中,我可以选择是否要使用在有或没有命名空间 std::中定义的类型

至少我的编译器 (g++ 4.7) 接受这两种变体。

我的问题是:使用 cstdint 中的 typedef 的推荐方法是什么。有或没有命名空间?有什么优点或缺点?还是只是风格问题?

所以变体 a):

#include <cstdint>
std::uint8_t n = 21;

回复:

#include <cstdint>
using std::uint8_t;
uint8_t n = 21;

或变体 b):

#include <cstdint>
uint8_t n = 21;

最佳答案

首选在 std 中声明的名称命名空间。原因在 §17.6.1.3/4(ISO/IEC 14882:2011(E),C++11)中给出:

Except as noted in Clauses 18 through 30 and Annex D, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in the C standard library (1.2) or the C Unicode TR, as appropriate, as if by inclusion. In the C++ standard library, however, the declarations (except for names which are defined as macros in C) 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).

如果您使用来自 <c 的名称姓名 >标题没有 std ,您的程序依赖于未指定的要求。

这在 C++03 和更早版本中有所不同,名称只应该出现在 std 中命名空间。然而,现实是许多实现只是简单地注入(inject) C 标准库头文件的内容 < 姓名 .h>进入std所以这在 C++11 中得到了适应。 C++03 标准的相应部分 (§17.4.1.2/4) 说:

Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause 7), as appropriate, as if by inclusion. In the C++ Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std.

此外,使用 std:: 限定名称有助于避免碰撞——如果你完全符合条件,你就会确切地知道你得到了什么。如果你真的要做 using namespace stdusing std::something ,至少在尽可能小的范围内进行。

关于c++ - 在带或不带命名空间的 <cstdint> 中使用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129945/

相关文章:

c++ - 派生类的虚表,除了父类虚函数外没有任何虚函数

c++ - 为什么 vector::operator[] 的实现方式与 map::operator[] 不同?

c++ - 特殊排序算法和通用签名

C++:ostream << 运算符错误

c++ - 在新代码中,为什么要使用 `int` 而不是 `int_fast16_t` 或 `int_fast32_t` 作为计数变量?

c++ - 如何在不使用变量 C/C++ 的情况下将常量数组文字传递给采用指针的函数?

c++ - 使用过多的功能

c++ - 泛化一个函数

c++如何在不同的枚举名称中具有相同的枚举成员名称而不会出现错误:redefinition; previous definition was 'enumerator'

c++ - STL vector 数据提取