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

后端 未结 2 1916
别那么骄傲
别那么骄傲 2021-01-04 08:15

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:



        
相关标签:
2条回答
  • 2021-01-04 08:51

    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
    
    0 讨论(0)
  • 2021-01-04 08:51

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

    0 讨论(0)
提交回复
热议问题