Search code examples
d

Access the generics arguments from a class in D


I have a class, that takes one generic argument

class A(T) {}

And I want to be able to access the value of that.

How can I do this.

I though that I might be able to write a function inside A that returns T, is this a good idea, or is there another way to access the type argument T outside the class A?


Solution

  • You can define an alias to T inside A that will return the actual "value" (type) of T. For example:

    class A(T)
    {
        alias type = T;
    }
    
    auto a = new A!int();
    assert(is(a.type == int));
    

    I've created a new A!int at runtime just for illustration. type is a sort of static member of A!T which you can access at compile time.

    assert(is(A!double.type == double));
    

    You can also easily extract the type that A was instantiated with using a template:

    alias InstantiationType(_: u!T, alias u, T) = T;
    assert(is(InstantiationType!(A!int) == int));
    

    Luckily, as was mentioned, this functionality comes prepackaged in Phobos' std.traits in the form of TemplateArgsOf.