为什么我的日志在std命名空间? [英] Why is my log in the std namespace?
问题描述
在下面的代码中,我定义了一个平凡的 log
函数。在 main
我尝试不来调用它;我叫 std :: log
。不过,我自己的 log
被调用;我看到日志!在屏幕上。有人知道为什么吗?我使用G ++ 4.7和clang ++ 3.2。
In the code below, I define a trivial log
function. In main
I try not to call it; I call std::log
. Nevertheless, my own log
is called; and I see "log!" on screen. Does anyone know why? I use G++ 4.7 and 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(强调我的):
C++ Standard 17.6.1.2 paragraph 4 (emphasis mine):
除了第18至30条和附件D中所述,每个标题
cname
应与C标准库(1.2)中指定的相应标题name.h
TR,视情况而定,如同通过包含。然而,在C ++标准库中,声明(除了在C中定义为宏的名称)在命名空间std
的命名空间范围(3.3.6)中。 未指定这些名称是否首先在全局命名空间范围内声明,然后通过显式的使用声明注入到命名空间std
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 headername.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 namespacestd
. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespacestd
by explicit using-declarations (7.3.3).
g ++使用后一种方法,因此一些相同的头文件可以重复使用C和C ++。因此,允许g ++在全局命名空间中声明和定义 double log(double)
。
g++ does it the latter way so that some of the same header files can be reused for C and C++. So g++ is allowed to declare and define double log(double)
in the global namespace.
第17.6.4.3节.3第3和第4段:
Section 17.6.4.3.3 paragraphs 3 and 4:
使用外部链接声明的标准C库中的每个名称都保留给实现以用作名称与
externC
链接,在命名空间std
中和全局命名空间中。
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 namespacestd
and in the global namespace.
使用外部链接声明的标准C库中的每个函数签名都保留给实现,用作具有 externC
和 externC ++
链接,或作为全局命名空间中的命名空间范围的名称。
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段的顶部:
And up at the top of Section 17.6.4.3 paragraph 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
。
You, on the other hand, may not declare or define ::log
in any way.
g ++工具链不会给你任何错误信息。
It's too bad the g++ toolchain doesn't give you any error messages, though.
这篇关于为什么我的日志在std命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!