When iterating over a standard container, do you think it\'s a good idea to omit the std:: prefix and rely on ADL to find the definition? Example:
If you're going to use ADL to be able to change the container type without changing the loops, then add using std::begin; using std::end;. That makes sure it finds the std functions for containers from other namespaces that have begin and end members, but no free functions in their namespace.
namespace my {
template <typename T>
struct container {
// ... stuff
iterator begin();
iterator end();
};
// no begin/end free functions
}
my::container<int> vec = get_vec();
using std::begin;
using std::end;
for (auto it = begin(vec), end = end(vec); it != end; ++it) { /*...*/ }
// defaults to std::begin which defaults to .begin() member function
do you think it's a good idea to omit the std:: prefix and rely on ADL to find the definition?
I think it is good idea. It becomes necessary in templates such as this:
template<typename Container>
void do_work(Container const & c)
{
using std::begin; //enable ADL
using std::end; //enable ADL
//now let compiler search the correct begin/end in the initialization part
for(auto it = begin(c), itend = end(c); it != itend ; ++it)
{
//do work
}
}
Here since Container can be a type defined by the programmer, say in namespace xyz, then how would the above function template work if I write std::begin instead of just begin (in the initialization part)?