I've read that to make one's custom container work with range-based for loop, "things" need to be in the same namespace. What things need to be in same namespace? The begin-end free functions and the iterator that it returns? Or the begin-end functions and the container passed to them?
3 Answers
begin and end need to be in the same namespace as the container/range type (or some other namespace associated with the type), because the range-for loop is specified to find them only via ADL.
That is assuming of course that you do not use the non-static member function approach, which is also fine for both.
That's all.
Comments
From Microsoft documentation, I understand that it is essential to ensure that the begin and end functions are accessible in the same namespace as your container. This accessibility allows the compiler to locate these functions through Argument-Dependent Lookup (ADL).
Comments
No it doesn't have to be (C++17) because of ADL, MRE to show this
#include <array> #include <iostream> namespace my_namespace { class my_collection { public: auto begin() { return m_data.begin(); } auto end() { return m_data.end(); } private: std::array<int,10> m_data{}; }; } int main() { my_namespace::my_collection collection; for(auto item : collection ) { std::cout << item << "\n"; } }