Patryk
Patryk

Reputation: 24130

Is there any reason find_if, for_each, count etc. do not require std::?

I have just came across the fact that several algorithms from standard algorithm header do not require std::.

Example:

#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

Is there any specific reason for that? Both g++ and clang++ accept the code above.

Upvotes: 1

Views: 362

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275800

There are two things going on here.

First is ADL, or Argument Dependent Name Lookup.

The functions are being found via ADL. This is because some of the arguments (namely, the vector's iterator type) are located in std, so when overload resolution looks for for_each, it looks in the usual set of namespaces (root in this case), plus ones determined by the namespaces of its arguments.

The trick is that vector::iterator is not guaranteed to be a type in namespace std. So your code is not guaranteed to work. It may be a type in std, or it could be a raw pointer, or it could be a type in namespace __std__utility_types, or anywhere else.

All major compiler libraries have vector iterators be not-pointers, and they are in namespace std, as the alternative is considered worse. But the lack of guarantee means you shouldn't rely on it for truly portable code.

Upvotes: 5

Related Questions