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

时间:2014-09-26 08:52:09

标签: c++ algorithm include std using

在某些情况下,似乎我可以访问应该在std命名空间中没有usingstd::限定符的函数。到目前为止,我只看到过algorithm库中的函数。

在下面的示例中,我希望all_of()位于std命名空间中,但此代码在VS2013(Microsoft编译器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;
}

std::cout更改为cout而不添加using namespace stdusing std::cout会生成&#34;未声明的标识符&#34;错误如预期。

这里发生了什么?

1 个答案:

答案 0 :(得分:3)

这可能是由Argument-Dependent Lookup引起的。 begin(text)end(text)返回的迭代器可能是在命名空间std中定义的类(或嵌套在命名空间std中的类中),这使得命名空间std与之相关联。查找函数调用的非限定名称会查找关联的命名空间,并在那里找到all_of

顺便说一句,这与调用begin(text)的工作原理完全相同,即使在命名空间begin()中定义了函数模板stdtextstd::basic_string,因此会搜索std

相关问题