Luke J. West <l...@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