template fiddling
Dmitry Olshansky
dmitry.olsh at gmail.com
Sat Aug 7 12:55:24 PDT 2010
On 07.08.2010 23:04, Blonder wrote:
> Hello,
> the template!(...) mechanism I understand.
> But I think I need the two classes, the first is the primary template
> and the second the partial specialization (this is the end of the "loop"), or can
> I do this in D with functions?
>
> The normal computation of the dot product is normally done in a for loop. But with
> templates you can enroll the loop.
> template!(...)(3, a, b). In this example 3 is the dimension of the arrays a and b.
>
>
Probably, this could be a starting point (BTW In D you can write
templates very easy):
T dot_product(size_t N, T)(T[] a, T[] b){
static if (N == 1){
return a[0] * b[0];
}else{
return a[0] * b[0] + dot_product!(N-1)(a[1..$],b[1..$]);
}
}
void main()
{
int[] a = [1, 2, 3];
int[] b = [5, 6, 7];
assert( dot_product!3(a,b) == 38 );//sanity check
}
And I didn't checked the disassembly.
> Andreas.
>
--
Dmitry Olshansky
More information about the Digitalmars-d-learn
mailing list