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;
}
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_eachin 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 suitablefor_each.The question that remains open is whether
std::vector<>::iteratorresides instd::or not. Clearly in your implementation it does, which is why the appropriatefor_eachinstd::is found. There may be cases where this iterator is not instd::– so to be safe (as in Alan’s comment), always get into the habit of qualifying withstd::.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).