Nobody understands templates?

sclytrack sclytrack at fake.com
Wed Mar 5 14:46:39 PST 2014


On Sunday, 2 March 2014 at 18:59:23 UTC, Steve Teale wrote:
> On Sunday, 2 March 2014 at 15:23:03 UTC, H. S. Teoh wrote:
>> This is a pretty good primer to templates:
>>
>> 	https://semitwist.com/articles/article/view/template-primer-in-d
>>
>>
>>
> The trouble is with most of these tutorials that they offer 
> examples that are things you would probably never want to do. I 
> can already add an int to an int, or a double to a double, or 
> an int to a double.
>
> Perhaps the examples should pick on something like vector 
> operations, but then who would be doing those with int, or some 
> class? It would be doubles or pairs of, as in struct Coord.




import std.stdio;
import std.algorithm;

void add(T,size_t N)(ref T[N] result, const T[N] a, const T[N] b)
{
   result[0] = a[0]+b[0];
   static if (N > 1)
     result[1]=a[1]+b[1];
}

void main()
{
	int [2] a = [1,2];
	int [2] b= [3,4];
	int [2] result;

	result.add(a,b);
	writeln(result);

	result[] = a[] + b[];
	writeln(result);
}


>
> I believe readers would study documentation and examples much 
> more carefully if they were things they might realistically 
> want to do. And that won't be type conversion - std.conv 
> already does a pretty good job on that. So what?
>
> We could really do with a place where template savvy open 
> source contributors could publish interesting examples of 
> template use.
>
> Otherwise, Joe Soap, like me, can spend a great deal of time 
> and effort in:
>
> a) Determining when the use of a template might be advantageous,
> b) Hacking at test programs to determine what the documentation 
> means, and what works, and what doesn't.
> c) After that, deciding whether it would be just as effective 
> to use two or three separate methods.
>
> Steve
>
>
> Steve

Are there any disadvantages of using a fixed size array for fixed 
size
coordinates and vectors, over creating an actual typedef or 
struct Vec3?



More information about the Digitalmars-d-learn mailing list