Is there a way to use Object.factory with templated classes? Or some way to construct templated classes given RTTI of an instance?

Chad Joan chadjoan at gmail.com
Thu Sep 27 05:18:14 UTC 2018


On Wednesday, 26 September 2018 at 21:25:07 UTC, Steven 
Schveighoffer wrote:
> ...
> Object.factory is a really old poorly supported type of 
> reflection. I would not depend on it for anything.
>

Roger that.  Will avoid :)

> You are better off using your own registration system.
>
> As far as choosing the design for your problem, you can use:
>
> auto obj = typeid(obj).create();
>
> which is going to work better, and doesn't require a linear 
> search through all modules/classes like Object.factory.
>

How does this work?

The language reference states that typeid(Type) returns "an 
instance of class TypeInfo corresponding to Type".
(https://dlang.org/spec/expression.html#typeid_expressions)

But then the TypeInfo class doesn't seem to have a .create() 
method, or at least not one in the documentation:
https://dlang.org/phobos/object.html#.TypeInfo

It looks like what I want, so it might be very helpful.

> If it were me, I'd probably instead implement a clone virtual 
> method. This way if any custom things need to occur when 
> copying the data, it can be handled.
>
> -Steve

I'm thinking I want to avoid the virtual method in this case, for 
reasons I wrote about in my response to Adam 
(https://forum.dlang.org/post/zovficijurwhuurrrfjf@forum.dlang.org).  But I think it's probably a good suggestion in most cases; I suspect that most of the time wanting to write a "deepCopy" method is going to be in response to some problem that will respond well to just virtualizing the method.

Thanks for the advice!


More information about the Digitalmars-d-learn mailing list