2

I'm playing around with my coding style. I used to explicitly prefix every library call with std:: but I'm switching over to using declarations like this:

using std::count;
using std::vector;

One thing I've noticed over the past few days is that sometimes if I forget a using declaration -- using std::vector; is a good example -- I get reams of compiler errors. However, if I neglect to namespace delcare an algorithm such as using std::count; my code compiles just fine.

Does this have to do with the difference with classes and free functions? On all the reference sites, both count(first, last, value) and vector are prefixed with std:: so I would expect them to behave the same.

Or does it have to do with other functions in the global namespace? I notice std::max also seems to require a namespace declaration, perhaps it defined in a default-included Apple/glibc/LLVM file and thus there is a conflict if I used it sans namespace declaration?

I am using Apple LLVM 7.0.2. on El Capitan.

EDIT: Show us the code

#include <algorithm>
#include <vector>

using std::count;
using std::vector;

int main() {
    vector<int> v = { 1, 2, 3, 4 };
    return count(begin(v), end(v), 3);
}

1 Answers1

5

As T.C. (almost) said, the magic incantation is ADL, which stands for "argument-dependent lookup". When a function is called with an argument whose type is defined in a namespace, the compiler looks for the function in that same namespace. Makes, sense, right?

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Got it. Is there any way to disable ADL in LLVM? Or at least visualize the lookup process? –  Jan 29 '16 at 22:28
  • @racarate - it's been less than a minute since I posted my answer, and less than 15 minutes since you posted the code that led to it. It's way too soon to accept it; someone else might post something that's absolutely brilliant and leads you into unforeseen depths of understanding. – Pete Becker Jan 29 '16 at 22:31
  • 1
    But you answered my question. I thought maybe free functions did not require namespace...-ing... but now I know in fact they do UNLESS their arguments happen to be in the same namespace. Your succinct answer indeed led me into unforeseen depths of understanding. –  Jan 29 '16 at 22:34