Nobody understands templates?
Chris
wendlec at tcd.ie
Mon Mar 3 14:35:05 PST 2014
On Monday, 3 March 2014 at 19:32:51 UTC, Dicebot wrote:
> On Monday, 3 March 2014 at 18:46:24 UTC, Chris wrote:
>> 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?
>
> What makes you think so? Template with specializations is still
> a template.
Maybe I'm a bit too philosophical about this. But consider the
following (made up) case:
struct MyTemp(T) {
// ...
T add(T a, T b) {
if (a is string && b is string) {
return a~b; // or return a~"+"~b; or whatever
} else if (a is integer && a is integer) {
return a+b;
}
}
}
I don't know if this can be considered a "pure" template. It is a
template of sorts, but the type specialization in the function
add makes it a watered-down template, imo. You could have a
version of MyTemp that handles only strings (and dchars, wchars)
and one that handles only numbers. But this you also have in OO
where this is achieved by inheritance and interfaces.
I think the confusion about templates often arises from the fact
that it is mainly about types, i.e. that the compiler fills in
the template with the appropriate type. But it is not an
abstraction of the logic behind a function. The logic in a+b is
the same for
int + int; float + float; float + int ... and thus not an
abstraction of adding one thing to another.
It is different for string + string. Of course, we can have
separate templates, one for numbers, one for strings, one for
arrays etc. But then it is less general. I am not against
templates, far from it, I like them, and std.algorithm is a
brilliant example of how useful they are. However, I wonder to
what extent they can be useful when writing a specialized program
as opposed to a general library. Walter mentioned that he uses
them a lot these days. How? I want to learn.
More information about the Digitalmars-d-learn
mailing list