Nobody understands templates?

Chris wendlec at tcd.ie
Mon Mar 3 10:46:23 PST 2014


On Monday, 3 March 2014 at 18:03:12 UTC, Frustrated wrote:
> On Sunday, 2 March 2014 at 11:47:39 UTC, Steve Teale wrote:
>> On Sunday, 2 March 2014 at 10:05:05 UTC, Dicebot wrote:
>>
>>>
>>> There is nothing wrong about not using templates. Almost any 
>>> compile-time design can be moved to run-time and expressed in 
>>> more common OOP form. And using tool you have mastery of is 
>>> usually more beneficial in practice than following the hype.
>>
>> Yes DB, we can soldier on happily, but it would not do any 
>> harm to understand templates.
>>
>> The documentation examples quickly make your eyes glaze over, 
>> looking at the code in Phobos is doubtless instructive, but 
>> you can wade through a lot of that without finding what you 
>> want. Also I discovered an interesting fact today. the word 
>> 'mixin' does not appear in the language reference Templates 
>> section of dlang.org.
>>
>> It should be used in at least one example. I just discovered 
>> by trial and error that I could use 'mixin' in Templates (as 
>> opposed to Template Mixins), and when you know that it seems 
>> likely that you can accomplish lots of stuff you couldn't 
>> before.
>>
>> While I'm here, has anyone discovered a way to fudge a 
>> constructor super(..) call in a mixin template that's included 
>> in a class constructor. Since the mixin template is evaluated 
>> in the scope of the constructor, it seems like it should be OK.
>>
>> I'm sure I'll get there in time ;=)
>>
>> Steve
>
> You've got to learn to think a bit more abstractly. Templates 
> are generalizations of things.

I think the problem is not that people don't understand templates 
in the sense that they are abstractions. The question is whether 
there are loads and loads of use cases for them.

> Suppose I want to add two numbers using a function.
>
> int add(int, int)?
> double add(double, int)?
> float add(float, int)?
> char add(char, double)?
> etc....
>
> which one? Do you want to have to create a function every time 
> for every time?

This is a typical use case and always mentioned in tutorials. The 
question is how many of these "typical" cases one encounters 
while writing software.

I think another problem with templates is that it is not always 
clear what is abstracted. The type or the logic? Both? In the 
above example the logic remains the same and is reproduced by the 
compiler for each type. Sometimes the logic can be abstracted for 
which type independence is important. But I'm not sure if that 
can be called a template in the purest sense. E.g. an algorithm 
that finds the first instance of something might be different for 
each type (string, char, int) and the "abstract" implementation 
has to differentiate internally (if string > else if int > else 
if ...). But this is no longer a template, or is it?

[snip]


More information about the Digitalmars-d-learn mailing list