foreach Support by Range Member Functions
Explore how to support foreach iteration in D by defining range member functions empty, popFront, and front within structs or classes. Understand how this enables safe and flexible looping over user-defined collections and integrates with range-based algorithms like retro for reverse iteration.
We'll cover the following...
foreach
As you remember from the foreach loop chapter, both how foreach works and the types and numbers of loop variables that it supports depend on the kind of collection:
-
For slices,
foreachprovides access to elements with or without a counter. -
For associative arrays, to values with or without keys; for number ranges, to the individual values.
-
For library types,
foreachbehaves in a way that is specific to that type, e.g., for File, it provides the lines of a file.
It is also possible to define the behavior of foreach for user-defined types. There are two methods of providing this support:
-
Defining range member functions, which allows using the user-defined type with other range algorithms as well
-
Defining one or more
opApplymember functions
Of the two methods, ...