1

I can do

std::vector<int> v;
begin(v);

yet, when I do

std::vector<int> v;
::begin(v);

I get

error: ‘::begin’ has not been declared ::begin(v);

It works again if I put

using namespace std;

at the top of the file, which I find weird, because I thought doing ::begin would actively prevent it from using std::begin. What is happening here?

Post Self
  • 1,471
  • 2
  • 14
  • 34
  • 2
    Read about: Argument dependent lookup: http://en.cppreference.com/w/cpp/language/adl put simply the namespace of any arguments is searched when trying to find the function. – Richard Critten Aug 14 '17 at 13:08
  • These functions are part of the `std` namespace, so why would you expect `::begin()` or `::end()` to work? – user0042 Aug 14 '17 at 13:08
  • @user0042 Because `begin(container)` works without `using namespace std;` – Post Self Aug 14 '17 at 13:09
  • I don't wonder about the error in 2nd sample. I wonder that the 1st works (without `using namespace std;`). I'm afraid I will never fully understand how names are resolved in C++... (That's why I'm using it carefully.) – Scheff's Cat Aug 14 '17 at 13:10
  • Ah, I now know. It was a duplicate. @Scheff look at the question linked. – Post Self Aug 14 '17 at 13:11
  • "Argument dependent lookup" would've been my guess - but nothing which I _know_ or even would dare to explain to anybody... I believe I stick to "using carefully"... – Scheff's Cat Aug 14 '17 at 13:16
  • This question could really use an answer which references the posting about Argument-Dependent Lookup (ADL). There are really two things going on here. The first is that ADL used by the compiler allows for the first use of `begin(v)` as the compiler matches up `std::vectorv` with the `begin()`. However the second use of `::begin(v)` changes what the compiler is doing since the use of `::` prevents the ADL search by the compiler. https://stackoverflow.com/questions/5345527/what-does-the-mean-in-c – Richard Chambers Aug 14 '17 at 13:19
  • @RichardChambers But it magically works again after `using namespace std`, though – Post Self Aug 14 '17 at 13:23
  • 2
    @kim366 `using namespace std` brings all the names in the `std` namespace into the global namespace. So the global namespace qualifier will now find them. This why `using namespace std` is such a bad thing to do. – Richard Critten Aug 14 '17 at 13:26
  • @RichardCritten Ah, I understand – Post Self Aug 14 '17 at 13:27

0 Answers0