Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relying on ADL for std::begin() and std::end()?

Tags:

c++

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:

std::vector<int> vec = get_vec();
// range-based for loop would be preferred here, but just for the sake of example
for (auto it = begin(vec), end = end(vec); it != end; ++it) { /*...*/ }

Are there any reasons to do or not do this?

like image 694
StackedCrooked Avatar asked Jun 28 '12 10:06

StackedCrooked


2 Answers

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
like image 172
R. Martinho Fernandes Avatar answered Sep 25 '22 12:09

R. Martinho Fernandes


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)?

like image 24
Nawaz Avatar answered Sep 23 '22 12:09

Nawaz