0

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?

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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"; } } 

2 Comments

I was talking about the free functions not the member functions but maybe did not say it clearly enough, sorry.
That's okay, it wasn't clear. Still in both cases ADL is at work :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.