Function pointer argument to function template
Daniel Keep
daniel.keep.lists at gmail.com
Wed May 31 03:32:09 PDT 2006
Tom S wrote:
> Daniel Keep wrote:
>> May as well ask this: do you know a simple way to infer both the number
>> and type of a function's arguments? I have a set of templates that can
>> do this, but they're somewhat ugly.
>
>
> Unfortunately I've got no idea as how to do it in a way that would
> detect more than primitive types as the arguments. My guess is that D
> would need more metainfo for functions or a means of converting a "type"
> to type (compile-time string to a compile-time identifier).
>
>
Actually, it's quite simple, if utterly evil. It involves abusing IFTI
in the most gruesome manner imaginable...
Detecting the number of arguments looks like this:
# typedef uint Arglen0 = 0;
# typedef uint Arglen1 = 1;
# typedef uint Arglen2 = 2;
# // and so on...
#
# template
# ArglenT(Tr)
# {
# Arglen0
# ArglenT(Tr function() fn) { assert(false); }
# }
#
# template
# ArglenT(Tr, Ta1)
# {
# Arglen1
# ArglenT(Tr function(Ta1) fn) { assert(false); }
# }
#
# template
# ArglenT(Tr, Ta1, Ta2)
# {
# Arglen2
# ArglenT(Tr function(Ta1, Ta2) fn) { assert(false); }
# }
#
# // Repeat ad absurdum
#
# template
# ArglenConvT(T)
# {
# const uint ArglenConvT = T.init;
# }
#
# template
# NumberOfArgsT(Tf)
# {
# private Tf fptr;
# alias typeof(ArglenT(fptr)) type;
# }
#
# public
# template
# NumberOfArgs(Tf)
# {
# const uint NumberOfArgs = ArglenConvT!(NumberOfArgsT!(Tf).type);
# }
What do you think of that sneaky use of typedefs? ^_^ Deducing the
return type, and argument types is pretty similar (except instead of
using ArglenN, you use Tr for the return type or Ta, Tb, Tc, etc for the
argument types).
The neat upshot of this is that despite using IFTI, I don't actually
think those functions ever get instantiated; they certainly never run,
which is kinda cool.
Thankfully, I have a nifty little Python script that saves me having to
actually *type* all that out. I give it a maximum number of arguments,
and it goes off and generates the template for me. Evil was never so easy!
I actually came up with this because I want to find a way to do
Boost-style Python embedding. So you can just use PyWrap(someFn) to
generate a Python wrapper for any old D function.
*drools at the thought of D+Python* Oops *mops up puddle*
-- Daniel
--
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d
mailing list