foreach filter by cast
karl via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Feb 14 17:45:05 PST 2015
I found a solution I like a lot, with templated opApply:
class Cont{
Thing[] kids;
int opApply(T)(int delegate(ref T) dg){
int result = 0;
for (int i = 0; i < kids.length; i++){
T t = cast(T)kids[i];
if(t){ result = dg(t);
if (result) break;
}
}
return result;
}
}
class Thing{
string name;
this(){ name = "thing";}
}
class TBan : Thing{
this(){ name = "tban";}
}
class TOne : Thing{
this(){ name = "tone";}
}
void main(){
Cont c = new Cont;
c.kids ~= new TBan;
c.kids ~= new TOne;
c.kids ~= new TOne;
c.kids ~= new Thing;
foreach(TOne k; c){ // the "TOne k" declares the filtering-type
writeln(k);
}
}
More information about the Digitalmars-d-learn
mailing list