Compile time variadic functions
Don Clugston
dac at nospam.com.au
Tue Mar 14 07:26:48 PST 2006
Oskar Linde wrote:
> Hello,
>
> I recently found out a way to use D's new implicit function template
> instantiation support to do compile time variadic functions
> (http://www.digitalmars.com/drn-bin/wwwnews?digitalmars.D/35151).I think
> it is cool enough to deserve its own post. :) I've added a slightly
> clumsy vararg declaration mixin to declare vararg functions.
>
> Here is a simple variadic function:
>
> template myFuncImpl(T) {
> void myFuncImpl(T) {
> static if (is (T == Empty)) {
> writefln("Done");
> } else {
> writefln("Got argument %s of type %s",args.head,
> typeid(typeof(args.head)));
> .myFuncImpl(T.tail); // tail-recurse
> }
> }
> }
>
> struct myFuncImplDummy { mixin decl_vararg_func!(myFuncImpl); }
> alias myFuncImplDummy.func myFunc;
>
> And here is how it's called:
>
> void main() {
> myFunc(1.0,2,3L);
> myFunc();
> }
>
> Is there any better way to do the decl_vararg_func and dummy struct
> thing?
Probably. But this is seriously cool already.
> An identifier name template parameter type would be awesome* (I
> would have other uses for that as well).
Alias parameters almost do that. I made qualifiednameof!(alias A),
prettynameof!(alias A) and symbolnameof!(alias A) templates which
convert identifier aliases to text. Is that any use?
> To be fully useful, one should add a conversion so that static array
> arguments are converted into dynamic arrays. Any other comments?
>
> Find the implementation including a (slightly updated) demo attached.
>
> /Oskar
>
> *) Another thing that would be nice is an auto (type inferred) return
> type for functions:
>
> auto func(int x) { return x+1; }
>
> Sometimes, I find myself having to write separate templates just to
> define a return type the compiler already knows. One example of one such
> template is TupleType in the attached code. (But I guess there might be
> a better way to write those templates...)
Sounds great, but could an auto function cope with 'if' ?
auto func(int x) {
if (x>2) return x+1;
else return Nasty!(SomeClass)(x);
}
In general, I think the compiler couldn't determine the type of an auto
function without evaluating the templates inside it...
More information about the Digitalmars-d
mailing list