例如,考虑 <cstdint>
header 。 C++ 标准 says :
The header defines all types and macros the same as the C standard library header
<stdint.h>
.
那么有没有必要用say std::int8_t
而不是短 C 形式 int8_t
在什么地方?
最佳答案
So is there a need to use say std::int8_t instead of the short C form int8_t somewhere?
是的。每[headers]/4 C 名称是否在全局 namespace 中定义是未指定的。因此你需要 std::int8_t
使用 int8_t
.它不保证 std::int8_t
存在,只是如果它确实存在,使用 std::int8_t
保证有效。
您可以只添加 using std::int8_t;
所以你不必输入 std::int8_t
到处都是。
[headers]/4 的相关部分是
In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope of the namespace std
强调我的
这意味着我们知道它们是在 std::
中声明的.部分
It is unspecified whether these names (including any overloads added in [language.support] through [thread] and [depr]) are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations ([namespace.udecl]).
然后允许名称位于全局命名空间中,但确实需要它。这让实现可以做类似的事情
<cstdint>
:
namespace std
{
#include <stdint.h>
}
或
<cstdint>
:
#include <stdint.h>
namespace std
{
using ::int8_t;
using ::int16_t;
//...
}
Bot 完成同样的事情(将名称放在 std::
中)并且是合法的实现,但只有第二个将名称放在全局范围内。
关于c++ std::types 而不是相应的 c 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53744128/