static foreach
Learn about the static foreach loop and how it is a more powerful compile-time feature than foreach.
We'll cover the following...
You saw compile-time foreach
earlier in the tuples chapter. Compile-time foreach
iterates the loop at compile-time and unrolls each iteration as separate pieces of code. For example, consider the following foreach
loop over a tuple:
Press + to interact
import std.stdio;import std.typecons;void main() {auto t = tuple(42, "hello", 1.5);foreach (i, member; t) {writefln("%s: %s", i, member);}}
The compiler unrolls the loop similar to the following equivalent code:
Press + to interact
{enum size_t i = 0;int member = t[i];writefln("%s: %s", i,member);}{enum size_t i = 1;string member = t[i];writefln("%s: %s", i, member);}{enum size_t i = 2;double member = t[i];writefln("%s: %s", i, member);}
Although very powerful, some properties of compile-time foreach may not be suitable in some cases:
-
With compile-time
foreach
...