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

Steven Schveighoffer schveiguy at gmail.com
Thu Sep 27 14:20:21 UTC 2018


On 9/27/18 1:18 AM, Chad Joan wrote:
> 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

typeid sometimes gives you a more derived type than TypeInfo. Including 
for classes and structs.

In the past, .classinfo gave you a different thing than typeid(obj), but 
now it is the same thing:


     auto obj = new Object;
     // classinfo and typeid are the same object
     assert(obj.classinfo is typeid(obj));
     // and the same type
     static assert(is(typeof(obj.classinfo) == typeof(typeid(obj))));

I wouldn't use classinfo any more, I generally use typeid.

-Steve


More information about the Digitalmars-d-learn mailing list