Get most D type from type

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 17 22:14:31 PDT 2017


On 03/17/2017 07:28 PM, Adam D. Ruppe wrote:
> On Friday, 17 March 2017 at 23:54:36 UTC, Hussien wrote:
>> What I need to do, is also get the D types that these use.
>
> Those aren't types, they are more like categories of type, so there's
> nothing in the language that can represent them to return (except maybe
> a string).
>
> Instead, you can test the family with the is expression, like so:
>
> static if(is(SomeEnum == enum))
>
> else static if(is(SomeClass == class))
>
> and so on. you could write a function that checks those (there are only
> i think 10 possibilities, enum, class, interface, struct, union,
> function, template, module, or basic type, or not a type at all) and
> return a string or whatever you choose to represent them.
>

I wrote the following before reading your reply:

None of those are concepts that you can capture i.e. you can't say:

     kind = class;

However, the 'is' expression can differentiate between them, in which 
case you can get e.g. a string out:

 
http://ddili.org/ders/d.en/is_expr.html#ix_is_expr.struct,%20is%20expression

template Kind(T) {
     static if (is (T == struct)) {
         enum Kind = "struct";
     }
     else static if (is (T == union)) {
         enum Kind = "union";
     }
     // etc.
     else {
         static assert("WAT!");
     }
}

unittest {
     struct S {}
     union U {}
     static assert(Kind!S == "struct");
     static assert(Kind!U == "union");
}

void main() {
}

Ali



More information about the Digitalmars-d-learn mailing list