function template specialization question D vs. C++
Adam D. Ruppe
destructionator at gmail.com
Sun Jan 14 02:31:45 UTC 2018
On Sunday, 14 January 2018 at 00:09:42 UTC, kdevel wrote:
> The compiler does not allow me to specialize the primary
> function template for double:
Yes, it does., and it works for float and double. Just `real`
matches both equally, so that's the error for that type. Let me
quote the spec:
https://dlang.org/spec/template.html#parameters_specialization
"The template picked to instantiate is the one that is most
specialized that fits the types of the TemplateArgumentList.
Determining which is more specialized is done in the same way as
the C++ partial ordering rules. If the result is ambiguous, it is
an error."
So, if there's only T:float, float, double, and real can all be
implicitly converted to that, so it is an exact match for float,
but a half-match for double and real, which are still better than
unspecialized T, so it matches that.
When you have T:float and T:double, then double, being an exact
match for the second one, triggers that. Similarly, float is
still an exact match for the first one, so that's the best. But
real is a half-match for both - it implicitly converts, but is
not exactly either. So it is ambiguous - the compiler doesn't
know which is a best fit.
You can add T:real to exactly match that, or use a constraint to
filter out real on one or both to remove it from consideration.
More information about the Digitalmars-d-learn
mailing list