【问题标题】:Is there any reason find_if, for_each, count etc. do not require std::?是否有任何理由 find_if、for_each、count 等不需要 std::?
【发布时间】:2017-05-03 05:57:08
【问题描述】:

我刚刚发现标准algorithm 标头中的几种算法不需要std::

例子:

#include <vector>
#include <algorithm>

int main() {
  std::vector<int> m;
  count(m.begin(), m.end(), 0);
  count_if(m.begin(), m.end(), [](auto){return true;});
  for_each(m.begin(), m.end(), [](auto){});
  find_if(m.begin(), m.end(), [](auto){return true;});
}

Live demo at coliru

有什么具体原因吗? g++clang++ 都接受上面的代码。

【问题讨论】:

标签: c++ algorithm c++11 std


【解决方案1】:

这里发生了两件事。

首先是 ADL,或Argument Dependent Name Lookup

这些函数是通过 ADL 找到的。这是因为某些参数(即vectoriterator 类型)位于std 中,因此当重载解析查找for_each 时,它会查找通常的命名空间集(根在此case),加上由其参数的命名空间确定的。

诀窍在于vector::iterator不保证namespace std 中的一个类型。所以你的代码不能保证工作。它可能std中的一个类型,或者它可能是一个原始指针,或者它可能是namespace __std__utility_types中的一个类型,或者其他任何地方。

所有主要的编译器库都将vector 迭代器作为非指针,它们在namespace std 中,因为替代方案被认为更糟。但缺乏保证意味着您不应该依赖它来实现真正可移植的代码。

【讨论】:

  • 我遇到了一个问题,即微软的 IDE 正在通过 ADL(他们的“编辑助手”IntelliSense)“找到”那些确切的功能,但在编译时编译器未能使用 ADL。
猜你喜欢
  • 1970-01-01
  • 2021-10-26
  • 2011-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 2011-11-25
相关资源
最近更新 更多