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

后端 未结 2 1932
别那么骄傲
别那么骄傲 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 
        struct container {
            // ... stuff
            iterator begin();
            iterator end();
        };
        // no begin/end free functions
    }
    
    
    my::container 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
    

提交回复
热议问题