Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why for_each works without std:: prefix

What i think is that for_each is defined in standard namespace, but this code actually compiles and runs with the following compiler flags. Can somebody please explain why?

  //@filename myprog.cpp 
  //g++-4.5 --std=c++0x myprog.cpp

  #include<iostream>
  #include<algorithm>

  int main()
  {
    std::vector<int> v{1,2,3,4,5};
    std::cout<<"printing the number\n";
    for_each(v.begin(),v.end(),[](int num) {//no std::for_each
        std::cout<<num<<"\t";
    });
 return 0;
 }
like image 972
A. K. Avatar asked Jul 18 '11 08:07

A. K.


1 Answers

Converting comment to answer, the reason this works is ADL (Argument Dependent Lookup). Basically what this means is that on failing to find a suitable match for for_each in the current namespace, the compiler has a built-in rule which says, now look in other namespaces - and the set of namespaces it uses for this are the namespaces of the arguments. Once it has a set of namespaces, it will search through them to find a suitable for_each.

The question that remains open is whether std::vector<>::iterator resides in std:: or not. Clearly in your implementation it does, which is why the appropriate for_each in std:: is found. There may be cases where this iterator is not in std:: - so to be safe (as in Alan's comment), always get into the habit of qualifying with std::.

Also this prevents any cases where someone else introduces another for_each (for arguments sake) in to your namespace - which may break things (in a worse case scenario - silently accepts - but breaks at run time).

like image 169
Nim Avatar answered Oct 23 '22 14:10

Nim