【问题标题】:Functions in namespace std accessible in global scope命名空间 std 中的函数可在全局范围内访问
【发布时间】:2014-09-26 08:52:08
【问题描述】:

在某些情况下,我似乎可以访问应该在 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 会按预期生成“未声明的标识符”错误。

这是怎么回事?

【问题讨论】:

  • 依赖于参数的查找?
  • @Niall 并不是真的重复,我会说。 std::string::const_iterator 是命名空间 std 中的一个类并不是很明显。
  • Google 搜索“命名空间 std cout 查找”无论如何都会产生 ADL
  • @Marco-A 好吧,但我不知道使用关键字“查找”。 ;)

标签: c++ algorithm include std using


【解决方案1】:

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

顺便说一句,这与调用begin(text) 的原因完全相同,即使函数模板begin() 定义在命名空间std 中。 textstd::basic_string,所以搜索到了 std

【讨论】:

  • 谢谢!这真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 2016-08-05
相关资源
最近更新 更多