有没有理由find_if,for_each,count等不需要std ::?

Pat*_*ryk 1 c++ algorithm std c++11

我刚刚发现标准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;});
}
Run Code Online (Sandbox Code Playgroud)

在coliru现场演示

这有什么具体原因吗?双方g++clang++接受上述代码.

Yak*_*ont 6

这里有两件事.

首先是ADL或Argument Dependent Name Lookup.

这些功能通过ADL找到.这是因为一些参数(即vectoriterator类型)位于std,所以当重载解析查找for_each,它看起来在平时的一套命名空间(根在这种情况下),以及那些通过它的参数的命名空间确定.

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

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