0

Why in c++, when I invoke std::sort, I have no error (even no warning) if I forget the namespace?

You can try with:

#include <algorithm>
#include <vector>

int main () {
  int init[] = {17,42,51,27,36,72,11,25};
  std::vector<int> myvector(init, init+8);
  sort(myvector.begin(), myvector.end()); //instead of std::sort
  return 0;
}

and then compile with:
g++ test.cpp -o test -Wall -Wextra -std=c++11

(Tested with g++ 4.9)

J.F.
  • 60
  • 6
  • Note that `std::vector::iterator` might be a simple pointer, and so no ADL and compilation error. – Jarod42 Aug 29 '16 at 12:33
  • Because of Argument Dependent lookup as assembly show this - `call void std::sort<__gnu_cxx::__normal_iterator > > >(__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > >)` – g-217 Aug 29 '16 at 12:38
  • Duplicate is poor, as it does not let the OP know about the perils of relying on it in this case, no? @iammilind – Yakk - Adam Nevraumont Aug 29 '16 at 12:40
  • @Yakk, duplicate is perfect for this case, because it addresses the OP's question: "Why no error?". Regarding "Perils", [an answer](http://stackoverflow.com/a/8111892/514235) discusses the same from that dupe. Other answers discusses about other aspects. In any case, if something is missed, then it will be best in interest of the community to add an answer in the linked dupe, rather than here. – iammilind Aug 29 '16 at 12:46
  • 1
    Thank you, `ADL` is the answer of my question. – J.F. Aug 29 '16 at 12:54
  • @iammilind The problem (why does this not generate an error?) is not answered by why it did not generate an error in this case; it is answered by both stating why this case generated no error, **and** that that is not guaranteed by the standard. Duplicate links should be links to answers that *fully answer* the question, not "mostly" answer. Such a post probably exists somewhere on SO. [For example](https://stackoverflow.com/questions/6803556/do-custom-container-iterators-guarantee-adl-to-consider-namespace-std), this directly addresses the OP's issue and the complications involved. – Yakk - Adam Nevraumont Aug 29 '16 at 13:05

0 Answers0