Template specialization ordering rules

Jonathan M Davis jmdavisProg at gmx.com
Sun Apr 10 13:15:26 PDT 2011


> Consider this template declaration: struct Foo(T : Bar!R, U = int, R) {}
> 
> As intended, it matches Foo!(Bar!float), with Bar being some other
> parametrized type and R being correctly inferred as float.
> 
> However, it doesn't seem to count as more specialized than just »struct
> Foo(T)« – for example, the following snippet produces an ambiguity error
> with the latest DMD 2 (0219a5f):
> 
> ---
> struct Foo(T) {}
> struct Foo(T : Bar!R, U = int, R) {}
> struct Bar(R) {}
> 
> Foo!(Bar!float) f;
> ---
> 
> Is this a bug or by design? http://digitalmars.com/d/2.0/template.html
> unfortunately just says »Determine which is more specialized is done the
> same way as the C++ partial ordering rules.«, which isn't really helpful
> if you don't have a copy of the C++ spec at hand…

C++ templates don't have the concept of : in them. Template specializes in C++ 
are only on exact type, not implicit conversion or inheritance. So, if C++ 
disambiguation rules are used exactly, then : would have to be ignored.

I think that the issue here is that Foo!(bar!float) works with _both_ 
templates. I don't remember what the exact rules are, but in my experience, D 
never chooses based on precedence. Things match exactly or there's an 
ambiguity. That being the case, you would have to make the first Foo so that 
it doesn't match _anything_ which matches the second one. To do that, you'd 
probably have to use a template constraint - something similar to

if(!is(T : Bar!R))

but you can't use quite that constraint because the first Foo has no R. So, it 
could be difficult to make it so that they don't match.

You could play around with more basic templates such as

struct Foo(T) {}
struct Foo(T : int) {}

and see whether they have the same problem. If they don't, then maybe you've 
actually found a bug. I don't know. Templates get to be a bit complicated when 
you have specializations. The general rule of thumb - if not absolute rule - 
is that they need to be written in such a way that they don't conflict at all.

- Jonathan M Davis


More information about the Digitalmars-d mailing list