简体   繁体   English

全局范围内可访问的命名空间std中的函数

[英]Functions in namespace std accessible in global scope

Under some situations, it seems like I can access functions that should be in the std namespace without a using or std:: qualifier. 在某些情况下,似乎无需usingstd::限定符就可以访问应该在std名称空间中的函数。 So far, I've only seen this occur with functions from the algorithm library. 到目前为止,我只看到algorithm库中的函数发生这种情况。

In the following example, I expect all_of() to be in the std namespace, but this code compiles without error in VS2013 (Microsoft Compiler 18). 在以下示例中,我希望all_of()位于std名称空间中,但是此代码在VS2013(Microsoft Compiler 18)中编译时没有错误。

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    const std::string text = "hey";
    std::cout << all_of(begin(text),end(text),islower);
    return 0;
}

Changing std::cout to cout without adding a using namespace std or using std::cout generates an "undeclared identifier" error as expected. 不添加using namespace stdusing std::coutstd::cout更改为cout按预期生成“未声明的标识符”错误。

What's going on here? 这里发生了什么?

This probably happens due to Argument-Dependent Lookup . 这可能是由于依赖参数的查找而发生的。 The iterator returned by begin(text) and end(text) is probably a class defined in namespace std (or nested in a class in namespace std ), which makes namespace std associated with it. begin(text)end(text)返回的迭代器可能是在名称空间std定义的类(或嵌套在名称空间std中的类中),这使名称空间std与之关联。 Looking up unqualified names for function calls looks into associated namespaces, and finds all_of there. 查找函数调用的不合格名称将查找关联的名称空间,并在其中找到all_of

By the way, this is exactly the same reason why calling begin(text) works, even though the function template begin() is defined in namespace std . 顺便说一句,这与调用begin(text)起作用的原因完全相同,即使函数模板begin()是在命名空间std定义的也是如此。 text is a std::basic_string , so std is searched. textstd::basic_string ,因此将搜索std

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM