On Wednesday, 26 September 2018 at 20:41:38 UTC, Chad Joan wrote:
I'm implementing a deep-copy method for a tree of templated
class instances. As part of this, I need some way to copy each
node.
[...]
that isn't already handled by their deepCopy method.
I would strongly suggest just using that virtual method and
having the child classes override it, then you call it from any
of them and get the right result.
Object.factory kinda sux and I'd actually like to remove it
(among other people). There's no plan to actually do that, but
still, just on principle I want to turn people away.
But even as you can see, the implementation is lacking and it
isn't great design anyway - the interface with virtual methods
does better work. It also wouldn't work in ctfe anyway,
object.factory relies on runtime stuff.
If Object.factory is incapable of this, is there some other
CTFE-friendly way to copy templated class instances?
I think you can copy typeinfo().init and then call
typeinfo().defaultConstructor - this is iirc what Object.factory
does, but once you already have the typeinfo you can use it
directly and bypass the string lookup.
But you'd really be better off with a virtual copy method. I say
those string factory things should only be used if you are
starting with a string, like deserialization.
interface Copyable {
Copyable copy();
}
class Whatever(T) : Copyable {
Whatever!T copy() {
auto c = new Whatever!T();
c.tupleof = this.tupleof;
return c;
}
}
that kind of method. the template implements the interface so
little boilerplate and it works and can be customized etc and
fits in well. If you call it from the interface, you get an
instance of the interface (tho note since it is virtual, the
underlying type is still what you need). If you call from the
child static type, you get it right back. Yay, fits liskov and
works!
If I have to, I can probably make these things register
themselves in some list of delegates that can be used to
instantiate the correct class. Or something like that. But I
am hoping that there is a better way that involves less
boilerplate.
that's not a terrible idea if you need delegates keyed to
strings...