【发布时间】:2020-03-19 21:57:06
【问题描述】:
据我了解,C++ 使用的 C 实体(如 <math.h> 中的实体)可以通过包含相应的 <c...> 变体以安全的方式包含在 std 命名空间中(显然,宏除外)。 cppreference seems to confirm this.
但是,包括 <cmath> 似乎会拉入 log 函数在std 命名空间之外:
#include <cmath>
namespace log {}
int main() {}
使用g++ -Wall -Wextra -pedantic -std=c++17 a.cpp 编译产生:
a.cpp:3:11: error: ‘namespace log { }’ redeclared as different kind of entity
3 | namespace log {}
| ^~~
In file included from /usr/include/features.h:446,
from /usr/include/x86_64-linux-gnu/c++/9/bits/os_defines.h:39,
from /usr/include/x86_64-linux-gnu/c++/9/bits/c++config.h:524,
from /usr/include/c++/9/cmath:41,
from a.cpp:1:
/usr/include/x86_64-linux-gnu/bits/mathcalls.h:104:1: note: previous declaration ‘double log(double)’
104 | __MATHCALL_VEC (log,, (_Mdouble_ __x));
| ^~~~~~~~~~~~~~
我的标准库坏了吗?我可以做些什么来避免这种情况吗?
我最初是在使用 <random> 时偶然发现的,这意味着更多的标头可能会受到明显随机的 C 实体的影响。
【问题讨论】:
-
"...以及相应的 cxxx 头文件也允许在全局命名空间中声明相同的名称..." 来源:en.cppreference.com/w/cpp/header
-
@RichardCritten Oh !@#$^% -- 这太疯狂了。有什么办法吗?
-
@bitmask: 将你的命名空间命名为其他名称,或者将其包装在另一个命名空间中?
标签: c++ namespaces std