Get template parameter value for your instance using properties D

Please excuse me if my terminology is incorrect.

Is it possible to determine the value of a type argument in an instance of a class template in the D programming language?

Please consider the following class structure:

class Entity {
}

class User : Entity {
}

class Collection(E:Entity) {
}

class UsersCollection : Collection!(User) {
}

Now, having access to the "UsersCollection", I can determine that this is a subclass of Collection, but I want to determine what type of entity the collection is ("User")

Here are my experiments:

import std.traits;

int main(){

        pragma(msg, BaseTypeTuple!UsersCollection);
        pragma(msg, TransitiveBaseTypeTuple!UsersCollection);
        pragma(msg, BaseClassesTuple!UsersCollection);
        //outputs:
        //(in Collection!(User))
        //(Collection!(User), Object)
        //(Collection!(User), Object)

        pragma(msg, UsersCollection);
        pragma(msg, isInstanceOf!(Collection, UsersCollection));
        //outputs:
        //UsersCollection
        //false

        foreach(BC; BaseClassesTuple!UsersCollection){
            pragma(msg, BC);
            pragma(msg, isInstanceOf!(Collection, BC));
        }
        //outputs:
        //Collection!(User)
        //true
        //Object
        //false

        return 0;
}

As you see the first BaseClassesTuple! UsersCollection is "Collection! (User)", but how to get "User" from it?

+4
source share
1 answer

is http://dlang.org/expression.html#IsExpression ( № 7 ):

    static if(is(BaseClassesTuple!UsersCollection[0] == Collection!Type, Type)) {
            // this is an instance of Collection
            // with the argument passed as Type
            pragma(msg, "MATCH!");
            pragma(msg, Type);
    }

, . , , , , , .

, "Collection! Type, Type" , Collection, Type .

if, . , Type if, , arg. .

+5

Source: https://habr.com/ru/post/1540518/


All Articles