| Thread overview | |||||
|---|---|---|---|---|---|
|
October 14, 2013 howto dispatch to derived classes? | ||||
|---|---|---|---|---|
| ||||
> class C{}
> class C1:C{}
> // ...
> class Cn:C{}
>
> C getC(){ return new Cn;} // might be extern
> // and deliver some Ci
>
> void visit( C1 fp){}
> // ...
> void visit( Cn fp){}
> void main(){
> visit( getC); // dispatch?
> }
-manfred
visit( getC);
}
| ||||
October 15, 2013 Re: howto dispatch to derived classes? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Manfred Nowak | On 10/14/2013 02:09 PM, Manfred Nowak wrote:
>> class C{}
>> class C1:C{}
>> // ...
>> class Cn:C{}
>>
>> C getC(){ return new Cn;} // might be extern
>> // and deliver some Ci
>>
>> void visit( C1 fp){}
>> // ...
>> void visit( Cn fp){}
>> void main(){
>> visit( getC); // dispatch?
>> }
>
> -manfred
>
> visit( getC);
> }
>
>
That it not exactly the same but looks like the visitor pattern. The actual type of the object is implicitly stored in the vtbl of each type. So, a virtual function like accept() can do the trick:
import std.stdio;
class C{
abstract void accept();
}
class C1:C {
override void accept() { visit(this); }
}
class Cn:C{
override void accept() { visit(this); }
}
C getC(){ return new Cn;} // might be extern
// and deliver some Ci
void visit( C1 fp) {
writeln("visiting C1");
}
void visit( Cn fp){
writeln("visiting Cn");
}
void main(){
getC().accept();
}
Ali
| |||
October 15, 2013 Re: howto dispatch to derived classes? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | =?UTF-8?B?QWxpIMOHZWhyZWxp?= wrote: > a virtual function like accept() can do the trick This would require changes in the whole class hierarchy. But because of > The actual type of the object is implicitly stored in the vtbl of each type. and in addition, because the statement | writeln( getC.classinfo.create.classinfo); gives the correct type there should be a possibility to dispatch to the correct `visit' function without any changes in the class hierarchy. I see that a sequence of statements | if( auto tmp= cast(Ci) getC) visit( tmp); can dispatch to the correct `visit' function. But this again would require knowledge of all `Ci'. A solution seems very close, but ... -manfred | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply