challenge #2: implement the varargs_reduce metafunction

Christian Kamm kamm at nospam.de
Tue Jan 23 07:25:08 PST 2007


> This one seems much more easy that the fist challenge, so I suspect I'm  
> missing something.

Your implementation doesn't work with template functions. Here's a rather  
straightforward implementation that seems to work:

template varargs_reduce(alias reduce2)
{
private:
   template ReduceType(ARGS...)
   {
     static assert(ARGS.length >= 2, "requires >= 2 arguments");

     static if(ARGS.length == 2)
       alias typeof(reduce2(ARGS[0], ARGS[1])) ReduceType;
     else static if(ARGS.length > 2)
       alias typeof(reduce2(ARGS[0], ReduceType!(ARGS[1..$]))) ReduceType;
   }
public:
   // I'd have prefered a typeof(result) or typeof(return) as return type  
here.
   ReduceType!(ARGS) varargs_reduce(ARGS...)(ARGS args)
   {
     static assert(args.length >= 2, "requires >= 2 arguments");
				
     static if(args.length == 2)
       auto result = reduce2(args[0], args[1]);
     else static if(args.length > 2)
       auto result = reduce2(args[0], varargs_reduce(args[1..$]));
	
     return result;
   }
}

typeof(T+Q) plus(T,Q)(T a, Q b)
{
   return a + b;
}

void main()
{
   alias varargs_reduce!(plus).varargs_reduce plus_va;
   plus_va(1, 2.1, 3i, 4u);
}

While it compiles and seems to behave correctly, I'm suspicious of my use  
of typeof in ReduceType - does the spec guarantee it does what I want? I  
tried using is and std.traits.ReturnType but typeof lead to the simplest  
solution.

Cheers,
Christian



More information about the Digitalmars-d mailing list