Function traits at compile time
Oskar Linde
oskar.lindeREM at OVEgmail.com
Mon Jun 12 08:19:34 PDT 2006
Victor Nakoryakov skrev:
> Hi all,
>
> Consider code:
>
> class MyClass(StructT)
> {
> ...
> }
>
> I know, that StructT has a function `foo` in it, but I don't know number
> of parameters and their types, of course. Does anybody knows a way to
> extract types to use them in `static if ( is(...) )` statements?
Hi,
This is possible but a bit tricky. You can use the compiler IFTI support
to extract this information. Make a template such as:
template delegateInfo(Ret, T1, T2, T3) {
Something!(Ret,T1,T2,T3) delegateInfo(Ret delegate(T1,T2,T3) x) {}
}
The template Something can then contain aliases for the different
argument types.
http://www.digitalmars.com/drn-bin/wwwnews?digitalmars.D/38553 has
already implemented such templates for you (just change the function
argument -> delegate and you should be able to do things like:
class MyClass(StructT) {
static if (funcInfo(&StructT.init.foo).numArgs == 1) {
pragma(msg,"StructT.foo takes 1 argument");
}
static if (is(typeof(funcInfo(&StructT.init.foo).Arg0Type)
== int)) {
pragma(msg,"First argument to StructT.foo is an int");
}
}
/Oskar
More information about the Digitalmars-d
mailing list