Supporting foreach (k, v; T.init) for a user-defined (container) type
H. S. Teoh
hsteoh at qfbox.info
Mon Oct 24 21:43:34 UTC 2022
On Mon, Oct 24, 2022 at 09:26:14PM +0000, Per Nordlöw via Digitalmars-d-learn wrote:
> What property of a container (type) `T` enables iteration as
>
> ```d
> foreach (k, v; T.init)
> {
> ...
> }
> ```
>
> ? I thought it sufficed to define `T.byKeyValue` but its presence seem
> to have no effect.
You want opApply.
Full working example:
------
struct A {
static int[string] impl;
static this() {
impl = [
"a": 1,
"b": 2,
];
}
int opApply(scope int delegate(string a, int b) dg) {
foreach (k, v; impl) {
auto r = dg(k, v);
if (r) return r;
}
return 0;
}
}
void main() {
import std;
A a;
foreach (k, v; a) {
writefln("%s -> %s", k, v);
}
}
------
T
--
Computers shouldn't beep through the keyhole.
More information about the Digitalmars-d-learn
mailing list