Getting derived classes

Jason House jason.james.house at gmail.com
Fri Oct 17 06:26:40 PDT 2008


Sean Kelly Wrote:

> dsimcha wrote:
> > == Quote from Andrei Alexandrescu (SeeWebsiteForEmail at erdani.org)'s article
> >> dsimcha wrote:
> >>> I know that, in std.traits, there's a template that spits out all base classes
> >>> for a given class.  Based on reading the source, it seems to work based on a
> >>> rather interesting use case for is expressions.  Is there any equivalent way
> >>> to do the opposite:  For any given position in a class hierarchy, to get a
> >>> tuple of all possible descendants?
> >> That's not possible in general because in D the derived classes form an
> >> open set. I guess it could be done at runtime via reflection (not
> >> implemented afaik), but not at compile time.
> >> Andrei
> > 
> > Not quite sure I understand why this has to be the case.  Somewhere in the docs,
> > Walter explicitly says that, since D knows about the whole class tree, the
> > compiler can figure out which functions in a hierarchy can be made non-virtual.
> > If this is the case, why is the compiler not able to know about the whole class
> > tree for purposes of creating lists of derived classes?
> 
> I think the actual implementation of this is somewhat different.  Rather 
> than relying on knowledge of the entire class tree, the compiler simply 
> has to know what type a particular function is being called on.  For 
> example:
> 
> class C
> {
>      void fn() {}
> }
> 
> void main()
> {
>      auto c = new C;
>      c.fn();
> }
> 
> Here, the compiler knows that it's dealing with an instance of C rather 
> than a possibly unknown derived class so it can call fn() directly 
> rather than going through the vtbl.  However:
> 
> void callFn( C c )
> {
>      c.fn();
> }
> 
> Here, the compiler doesn't know what the underlying type is so it must 
> go through the vtbl.
> 
> 
> Sean

The compiler could be smarter than that, but isn't. I too was tricked by the same bit of D documentation. Avoiding virtual calls can be a significant speed gain. I have final functions throughout my code because gdc was too stupid to recognize they could be.



More information about the Digitalmars-d mailing list