c++ - 为什么我的日志在 std 命名空间中?

标签 c++ namespaces overloading

在下面的代码中,我定义了一个简单的 log 函数。在 main 中,我尝试调用它;我调用 std::log。尽管如此,还是调用了我自己的log;我看到“日志!”在屏幕上。有谁知道为什么?我使用 G++ 4.7 和 clang++ 3.2。

#include <iostream>
#include <cmath>

double log(const double x) { std::cout << "log!\n"; return x; }

int main(int argc, char *argv[])
{
  std::log(3.14);
  return 0;
}

最佳答案

C++ 标准 17.6.1.2 第 4 段(强调我的):

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).

g++ 以后一种方式实现,因此一些相同的头文件可以被 C 和 C++ 重用。所以g++被允许在全局命名空间中声明和定义double log(double)

第 17.6.4.3.3 节第 3 和第 4 段:

Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.

Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++"linkage, or as a name of namespace scope in the global namespace.

在第 17.6.4.3 节第 2 段的顶部:

If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.

另一方面,您可以以任何方式声明或定义::log

可惜 g++ 工具链没有给你任何错误信息。

关于c++ - 为什么我的日志在 std 命名空间中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43500813/

相关文章:

c++ - 没有可行的重载

c++ - 在 vector 使用中找不到 fatal error

c++ - Qt 项目链接面临 undefined reference

swiftui - 如何避免与 SwiftUI 中的嵌套结构命名冲突?

python:从外部代码导入 numpy 作为 np 在我自己的用户定义模块中丢失

c++ - 重载一个简单的 = 运算符

c++ - 在按钮中实例化类的范围问题

javascript - 使用命名空间时 jQuery bind() 的行为

c++ - 内部模板类型 std::vector<std::vector<T>> 的函数模板重载或专门化

c++ - 使用 std::tie 比较结构