Search⌘ K
AI Features

opApply & opApplyReverse Member Functions

Explore how to implement and use opApply and opApplyReverse member functions in D to enable custom iteration in foreach loops. Understand the convention behind opApply calls, how to write them for structs and classes, and how overloads allow iterating an object in multiple ways. This lesson equips you to design flexible and efficient loops for your D types.

foreach, opApply, and opApplyReverse

Everything that is said about opApply in this section is valid for opApplyReverse as well. opApplyReverse is for defining the behaviors of objects in the foreach_reverse loops.

The member functions above allow us to use objects as ranges. That method is more suitable when there is only one sensible way of iterating over a range. For example, it would be easy to provide access to individual students of a Students type.

On the other hand, sometimes it makes more sense to iterate over the same object in different ways. We know this from associative arrays, where it is possible to access either only to the values or to both the keys and the values:

string[string] dictionary;    // from English to Turkish

// ...

foreach (inTurkish; dictionary) {
    // ... only values ...
}
foreach (inEnglish, inTurkish; dictionary) {
    // ... keys and values ...
}

opApply allows using user-defined types with foreach in various and sometimes more complex ways. Before learning how to define ...