Function pointer argument to function template

Bruno Medeiros brunodomedeirosATgmail at SPAM.com
Sat Jun 3 10:28:11 PDT 2006


Tom S wrote:
> 
> How about taking it a step further and doing something like:
> 
> ----
> import std.stdio;
> 
> struct FuncMeta(int NumArgs, Ret, T0=void, T1=void /+, and, so, on+/) {
>     alias FuncMeta Meta;
> 
>     static const int    numArgs = NumArgs;
>     alias    Ret            RetType;
>     alias    T0            Arg0Type;    // these might use static if as 
> well
>     alias    T1            Arg1Type;
>     /+
>     ... and so on
>     +/
> }
> 
> 
> template funcInfo(Ret) {
>     FuncMeta!(0, Ret) funcInfo(Ret function() x) { assert(false); };
> }
> 
> 
> template funcInfo(Ret, T0) {
>     FuncMeta!(1, Ret, T0) funcInfo(Ret function(T0) x) { assert(false); };
> }
> 
> 
> template funcInfo(Ret, T0, T1) {
>     FuncMeta!(2, Ret, T0, T1) funcInfo(Ret function(T0, T1) x) { 
> assert(false); };
> }
> 
> /+
> ....
> 
> template funcInfo(Ret, T0, T1, ..., Tn) {
>     ...
> }
> +/
> 
> 
> struct Foo {}
> void fooFunc(Foo a, float b) {}
> int barFunc(cfloat x) {}
> 
> 
> void main(char[][] args) {
>     writefln("Number of args of main: ", funcInfo(&main).numArgs);
> 
>     writefln("\nfunc foo:");
>     alias typeof(funcInfo(&fooFunc)) FooMeta;
>     writefln(FooMeta.numArgs);
>     writefln(typeid(FooMeta.RetType));
>     writefln(typeid(FooMeta.Arg0Type));
>     writefln(typeid(FooMeta.Arg1Type));
> 
>     writefln("\nfunc bar:");
>     alias typeof(funcInfo(&barFunc)) BarMeta;
>     writefln(BarMeta.numArgs);
>     writefln(typeid(BarMeta.RetType));
>     writefln(typeid(BarMeta.Arg0Type));
> 
>     static if (BarMeta.numArgs >= 2) {
>         writefln(typeid(BarMeta.Arg1Type));
>     } else {
>         writefln("bar doesn't have Arg1Type");
>     }
> }
> 
> 
> Note that the ArgXType could be static if'fed away so one would get an 
> error when trying to access them instead of having them alias to void.
> 
> 

Hum, pretty nice!

-- 
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list