challenge #2: implement the varargs_reduce metafunction

Lutger lutger.blijdestijn at gmail.com
Tue Jan 23 09:18:52 PST 2007


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

I suspect the same since I have just a few lines. This is what I came up 
with, does it meet the requirements? There must be something wrong.

template reduce(alias fn)
{
     typeof(T[0]) reduce(T...)(T args)
     {
         static assert( is(T[0] == T[1]) &&
                        is( T[0] == typeof( fn(T[0], T[1]) ) ),
                        "try again" );
         static assert( args.length > 1, "nothing to reduce here");

         auto result = args[0];
         foreach(arg; args[1..$])
             result = fn(result, arg);
         return result;
     }
}

example:

alias reduce!(function(int a, int b) { return (a > b) ? a : b; }) max;
assert( max(2,55,787) == 787 );



More information about the Digitalmars-d mailing list