Compile time variadic functions

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Mar 13 12:01:08 PST 2006


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? An identifier name template parameter type would be awesome* (I 
would have other uses for that as well).

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...)

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: varargs.d
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20060313/02d2d671/attachment.ksh>


More information about the Digitalmars-d mailing list