Possible to avoid downcasting?

Adam D. Ruppe destructionator at gmail.com
Tue Dec 24 20:15:32 UTC 2019


On Tuesday, 24 December 2019 at 19:52:44 UTC, H. S. Teoh wrote:
> But I want to have the option of creating the tree with derived 
> class nodes instead of BaseNode.  One option is to pass a 
> factory function to makeTree():
>
> 	BaseNode makeBaseNode() { return new BaseNode(...); }

You can also, if this is in the class, make it virtual and have 
the child classes return instances of themselves when overriding.

> Is there a template equivalent of inout functions, where you 
> basically say "the return type depends on the template 
> parameter, but otherwise the function body is identical, so 
> don't bother creating a new instantiation, just reuse the same 
> function body"?

But this is easy enough with traditional function techniques:

private void populate(Base b) { /* guts that only need to know 
base; most your makeTree function */ }

public T make(T)() {
    auto t = new T();
    populate(t);
    return t;
}


So now the templated section is reduced to really just the 
constructor call... and realistically the compiler can pretty 
easily inline that as well.

No cast, minimal duplication, easy to use on the outside.

(tbh i think sometimes we get so excited about D's cool features 
that we forget about the simple options we have too!)


speaking of cool features though


void populate(Object o) {
         import std.stdio;
         writeln(o);
}

// the lazy here....
T make(T)(lazy T t) {
         populate(t);
         return t;
}

class Foo {}

void main() {
         // means the new Foo down there is automatically 
lambdaized
         auto tree = make(new Foo);
}


which might be kinda fun.


More information about the Digitalmars-d mailing list