detecting classes, structs, arrays in templates

Simen kjaeraas simen.kjaras at gmail.com
Sun Jan 23 06:03:10 PST 2011


Luke J. West <luke at west.me.uk> wrote:

> Hi,
>
> I want to specialize a template function - call it print() - for three
> cases: classes, structs and arrays. Ideally I'd like something that
> looks 'functional' like a proper specialization, but perhaps I need to
> use "static if". I'm still at the beginning of my journey with D so I'd
> be grateful for any pointers (sorry - that's a terrible pun). Perhaps
> there's a corner of the D2 docs I've glossed over.
>
> Thanks,
>
> Luke
>
>
> // in words you can understand...
>
> void print(T)() {writefln("general");}
>
> // But what does my specialization look like for all (or any)
> // of the implementations of print() for the calls below.
>
> int main() {
>  C   c;    // some class
>  S   s;    // some struct
>  int a[4]; // an array
>  int p;    // a primitive type
> print(c); // writefln("class");
>  print(s); // writefln("struct");
>  print(a); // writefln("array");
>  print(p); // writefln("primitive");
>
>  return 0;
> }

You want to have a look-see at isExpressions[1]:

void print(T)(T t) if (is(T == class)){
     writeln("class");
}

void print(T)(T t) if (is(T == struct)){
     writeln("struct");
}

void print(T)(T t) if (is(T U == U[])){
     writeln("array");
}

void print(T)(T t) if (isNumeric!T || isSomeChar!T){
     writeln("primitive");
}

Haven't actually tested these, as I don't have D here.

Note also that two specializations are missing - pointer
and associative array:

void print(T)(T t) if (is(T U == U[V], V)){
     writeln("associative array");
}

void print(T)(T t) if (is(T U == U*)){
     writeln("pointer");
}

http://digitalmars.com/d/2.0/expression.html#IsExpression

-- 
Simen


More information about the Digitalmars-d mailing list