Can't understand templates

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 28 15:59:06 PST 2014


On 11/28/2014 12:36 PM, Sly wrote:

 > Let's take a simpler example from earlier in the tutorial, where
 > Point is a non-template struct:
 >
 >
 > // The general definition of the function template (same as
 > before)
 > T getResponse(T)(string question)
 > {
[...]
 > }

That definition would work with any type T. So, it is general: it 
accepts any type.

 > // The specialization of the function template for Point
 > T getResponse(T : Point)(string question)
 > {
[...]
 > }

That definition is for T that matches Point (i.e. Point itself in this 
example). So, it is special: it accepts only that type.

 > auto center = getResponse!Point("Where is the center?");
 >
 > Doesn't getResponse!Point match both declarations?

True but the call is dispatched to the most special of all of the 
matches. It is very briefly explained through a reference to C++:

"The template picked to instantiate is the one that is most specialized 
that fits the types of the TemplateArgumentList. Determine which is more 
specialized is done the same way as the C++ partial ordering rules. If 
the result is ambiguous, it is an error."

See the "Specialization" heading here:

   http://dlang.org/template.html

Ali



More information about the Digitalmars-d-learn mailing list