Search code examples
typesd

Can I create a struct out of a TypeInfo_Struct?


I have a TypeInfo_Stuct; how do I create a struct out of this?

struct A {
    int example;
}

TypeInfo test = typeid(A);

void main() {
    // how do I create a structure of type A from test in here? 
}

Solution

  • I don't think it is possible. It implies polymorphic construction which is not provided for structs in D.

    Such functionality is supported by druntime for classes though:

    class A {}
    
    auto ti = typeid(A);
    
    void main()
    {
        auto instance = cast(A) ti.create();
        assert(instance);
    }
    

    One can possibly implement similar factory infrastructure for types other than classes but that is not available out of the box (and is somewhat discouraged).