template fiddling

Mafi mafi at example.org
Sat Aug 7 10:18:27 PDT 2010


Am 07.08.2010 18:40, schrieb Blonder:
> Hello,
>
> I am trying to understand the template mechanism in D, but I don't get it working.
>
> I want to compute the dot product as follows:
> 	int[] a = [1, 2, 3];
> 	int[] b = [5, 6, 7];
>
> 	double dd = ???.dot_product( a, b );
>
> with classes like this:
> class DotProduct(DIM, T)
> {
> 	static T result(T a, T b)
> 	{
> 		return a * b + DotProduct!(DIM-1, T).result(a+1, b+1);
> 	}
> }
>
> class DotProduct(1, T)
> {
> 	static T result(T a, T b)
> 	{
> 		return a * b;
> 	}
> }
>
> and a function :
> T dot_product(DIM a, T b)
> {
>    return ???.result( a, b );
> }
>
> Can anyone help me? In C++ its not the problem but with D I can't
> get it working.
>
> Thanks,
> Andreas

Hi,
to make an instance of an template you use the !-infix operator: 
'template!(param,...)'. If you want to give only one parameter you can 
use 'template!param'. But your example can't work because template 
arguments have to be evaluatable at compile time (which function 
parameters are not). You can use a normal function parameter.

In your example you use a template class which isn't supposed to be used 
as class, I think. If so, you should make a simple template
template MyTemplate(.......){
   int myFunction(....){}
   int myFunction2(....){}
}
Then you can say MyTemplate!(...).myFunction(...). You can leave out 
tralling template arguments which deducable by the arguments of the 
function.

There also a trick that you can use to make a shortcut. Add
   alias MyTemplate myFunction
to the template. Then you can use MyTemplate!(....)(....)instead of 
MyTemplate!(.....).myFunction(....). MyTemplate!(....).myFunction2(....) 
will still work.

The above trick is also how class and function templates work.

Mafi


P.S. If you often use some template instance you can use an alias
   alias MyTemplate!(.....) MyInstance


More information about the Digitalmars-d-learn mailing list