Why Templates?
Sean Kelly
sean at f4.ca
Sat Mar 4 16:10:26 PST 2006
Derek Parnell wrote:
> I'm sure its because I'm not from a C++ background, but I just don't get
> templates. What is the problem that Templates solve?
>
> From my limited experience they just seem to be a shorthand for a way
> of avoiding coding identical algorithms that only vary in the datatypes
> that are passed to them. Is that it or am I missing some fundamental
> elements?
That was the original intent. As far as I know, the original idea came
from Alexander Stepanov (http://www.stepanovpapers.com/), who is also
responsible for generics in Ada. But since their introduction,
templates have also shown to be a useful high-performance alternative to
run-time polymorphism, not to mention the more advanced code-generation
trickery that has become so popular in the C++ world.
> And is that why people are clamoring for implicit template instantation
> - to further reduce the amount of typing to do (and remembering to
> instantiate the only the required renditions of the algorithm).
For the most part, yes, as template names can become quite long, and
calling functions as:
fn!(typeof(a),typeof(b))(a,b);
is a bit annoying and reduces readability. ITI is also quite useful in
C++ with respect to how overload resolution is handled, but I have no
idea how this will translate to the far simpler overloading rules in D.
I think we really may have to simply want and see what Walter comes up
with for ITI in D, as simply eliminating the need to explicitly specify
template parameters doesn't encompass the full utility of ITI in C++.
Will we be able to overload template functions with each other? Will
they also overload with non-template functions? What happens if there
are multiple matches?
class C(T) {}
template func(T) { void func( T val ) {} }
template func(T) { void func( C!(T) val ) {} }
void func( C!(int) val ) {}
func( new C!(int) );
In C++, this is legal and the result is clearly defined (the "most
specialized" overload is called), but how will this translate to D?
Will it even be legal?
Sean
More information about the Digitalmars-d
mailing list