d的opApply只是个闭包
import std.stdio;
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() {
A a;
foreach (k, v; a) {
writefln("%s -> %s", k, v);
}
}
d的opApply只是官方的一个稍微高阶的闭包罢了.每一的{}作为闭包内容,相当于策略类插入到opApply的基础类里面!是不是策略类到处都有?
应该这样理解,类是插件.把类当作{}块.插入基块中.而不是函数作插件,函数作插件没有类作插件方便,舒服!
而真正的函数与类的公共基块应该是{}块.以{}为基块,当然编译过程中就是这样处理的.{}为基块.
浙公网安备 33010602011771号