what is the preferred way to expose custom STL-style iteration?

前端 未结 4 1909
春和景丽
春和景丽 2020-12-19 04:47

(also see Is there a good way not to hand-write all twelve required Container functions for a custom type in C++? )


For a class such as

namespa         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 05:22

    I'll take option C.

    The main problem here is that std::begin() doesn't actually work for finding non-member begin() with ADL. So the real solution is to write your own that does:

    namespace details {
        using std::begin;
    
        template 
        constexpr auto adl_begin(C& c) noexcept(noexcept(begin(c)))
            -> decltype(begin(c))
        {
            return begin(c);
        }
    }
    
    using details::adl_begin;
    

    Now, it doesn't matter if you write your begin() as a member or non-member function, just use adl_begin(x) everywhere and it'll just work. As well as for both the standard containers and raw arrays. This conveniently side-steps the member vs. non-member discussion.


    And yes, you should have const and non-const overloads of begin() and friends, if you want to expose const and non-const access.

提交回复
热议问题