When you want to use a user-defined type in a range-based for-loop, your user-defined type has to implement the Iterator Protocol.
Here is the question I want to answer: What interface must a user-defined type support to be usable in a range-based for-loop.
Requirements of a Range-Based for-Loop
Let me start with a simple experiment and use
std::array in C++ Insights. Here is a simple example:
C++ Insights creates the following code out of it:
Let me write it more generally: When you use a range-based for-loop (
for(range_declaration : range_expression)), the compiler creates the following code:
I marked the essential parts in red:
end_expr: return an iterator object
- Iterator object
operator++: incrementing the iterator
operator*: dereferencing the iterator and accessing the current element
operator!=: comparing the iterator with another iterator
end_expr call the essential
end on the range_expression. begin and end could either be member functions or free functions on range_expression.
Let me apply the theory and create a number generator.
My first implementation supports the Iterator Protocol
The Iterator Protocol
The following class
Generator supports the elementary Iterator Protocol.
Generator has member functions
end, (lines 1 and 2)
end_. begin_ and
end_ stand for the range of created numbers. Let me analyze the inner class
Iterator which keeps track of the generated numbers:
operator*returns the current value
operator++increments the current value
operator!=compares the current value with the
Finally, here is the output of the program:
Let me generalize the iterator returned by
end() and make it a forward iterator. Afterward, the class
Generator can be used in most of the algorithms of the Standard Template Library. To put it differently, the unordered associative containers support a forward iterator.
A Forward Iterator
The following improved
Generator has an inner class Iterator that is a forward iterator.
Iterator needs several type aliases in the following member function declarations. Additionally, to the previous
Iterator implementation in the program
iterator.cpp, the current Iterator supports the following member functions: the arrow operator (
operator-> in line 2), the post-increment operator (
operator++(int) in line 3), and the equal operator (
operator== in line 4).
That was it already. Now, I can use my improved
Generator still in a range-based for-loop (line 5), but also in the STL algorithm
std::accumulate. Line 6 calculates the sum of all numbers from 1 to 10; line 7 does a similar job by multiplying numbers from 1 to 11. In the first case, I choose the neutral element 0 for the summation, and in the second case the neutral element 1 for the multiplication.
There is a subtle difference between the first and the second call of
std::accumulate. The first call uses the non-member functions
std::end on the Generator:
std::accumulate(std::begin(gen), std::end(gen), 0), but the second call the
Generator's member functions
end() directly which I implemented.
Finally, here is the output of the program:
In my next post, I will write about the Covariant Return Type. The Covariant Return Type of a member function allows an overriding member function to return a narrower type. This is particularly useful when you implement the creational design pattern Prototype.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, and Bhavith C Achar.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,