Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

partial specialization ordering with non-deduced context

According to [temp.class.order] §14.5.5.2, the selection of a partial specialization of t in this example:

template< typename >
struct s { typedef void v, w; };

template< typename, typename = void >
struct t {};

template< typename c >
struct t< c, typename c::v > {};

template< typename c >
struct t< s< c >, typename s< c >::w > {};

t< s< int > > q;

is equivalent to the selection of an overload of f in this example:

template< typename >
struct s { typedef void v, w; };

template< typename, typename = void >
struct t {};

template< typename c >
constexpr int f( t< c, typename c::v > ) { return 1; }

template< typename c >
constexpr int f( t< s< c >, typename s< c >::w > ) { return 2; }

static_assert ( f( t< s< int > >() ) == 2, "" );

However, GCC, Clang, and ICC all reject the first example as ambiguous, but accept the second.

Even more strangely, the first example works if ::v is replaced with ::w or vice versa. The non-deduced contexts c:: and s< c >:: are apparently being considered in specialization ordering, which doesn't make sense.

Am I missing something in the standard, or do all these implementations have the same bug?

like image 324
Potatoswatter Avatar asked Jul 19 '15 02:07

Potatoswatter


People also ask

Why are partial specializations of the member template ignored?

If the primary member template is explicitly (fully) specialized for a given (implicit) specialization of the enclosing class template, the partial specializations of the member template are ignored for this specialization of the enclosing class template.

What is the difference between primary and partial specialization?

Explicit (full) specialization of a member of a partial specialization is declared the same way as an explicit specialization of the primary template. If a primary template is a member of another class template, its partial specializations are members of the enclosing class template.

What is the difference between first partial specialization and first function template?

the first function template has the same template parameters as the first partial specialization and has just one function parameter, whose type is a class template specialization with all the template arguments from the first partial specialization

How to determine which specialization is more specialized in C++?

1) If only one specialization matches the template arguments, that specialization is used 2) If more than one specialization matches, partial order rules are used to determine which specialization is more specialized. The most specialized specialization is used, if it is unique (if it is not unique, the program cannot be compiled)


1 Answers

Switching to extremely-pedantic-mode for a moment, yes, I think you are missing something in the standard, and no, it shouldn't make any difference in this case.

All standard references are to N4527, the current working draft.

[14.5.5.2p1] says:

For two class template partial specializations, the first is more specialized than the second if, given the following rewrite to two function templates, the first function template is more specialized than the second according to the ordering rules for function templates (14.5.6.2):

  • the first function template has the same template parameters as the first partial specialization and has a single function parameter whose type is a class template specialization with the template arguments of the first partial specialization, and
  • the second function template has the same template parameters as the second partial specialization and has a single function parameter whose type is a class template specialization with the template arguments of the second partial specialization.

Going to [14.5.6.2p1]:

[...] Partial ordering of overloaded function template declarations is used in the following contexts to select the function template to which a function template specialization refers:

  • during overload resolution for a call to a function template specialization (13.3.3);
  • when the address of a function template specialization is taken;
  • when a placement operator delete that is a function template specialization is selected to match a placement operator new (3.7.4.2, 5.3.4);
  • when a friend function declaration (14.5.4), an explicit instantiation (14.7.2) or an explicit specialization (14.7.3) refers to a function template specialization.

No mention of partial ordering of class template specializations. However, [14.8.2.4p3] says:

The types used to determine the ordering depend on the context in which the partial ordering is done:

  • In the context of a function call, the types used are those function parameter types for which the function call has arguments.
  • In the context of a call to a conversion function, the return types of the conversion function templates are used.
  • In other contexts (14.5.6.2) the function template’s function type is used.

Even though it refers back to [14.5.6.2], it does say "other contexts". I can only conclude that, when applying the partial ordering algorithm to the function templates generated according to the rules in [14.5.5.2], the function template’s function type is used, not the list of parameter types, as it would happen for a function call.

So, the selection of a partial specialization of t in your first snippet would be equivalent not to a case involving a function call, but to one that takes the address of a function template (for example), which also falls under "other contexts":

#include <iostream>

template<typename> struct s { typedef void v, w; };
template<typename, typename = void> struct t { };

template<typename C> void f(t<C, typename C::v>) { std::cout << "t<C, C::v>\n"; }
template<typename C> void f(t<s<C>, typename s<C>::w>) { std::cout << "t<s<C>, s<C>::w>\n"; }

int main()
{
   using pft = void (*)(t<s<int>>);
   pft p = f;
   p(t<s<int>>());
}

(Since we're still in extremely-pedantic-mode, I rewrote the function templates exactly like the example in [14.5.5.2p2].)

Needless to say, this also compiles and prints t<s<C>, s<C>::w>. The chances of it producing different behaviour were slim, but I had to try it. Considering how the algorithm works, it would have made a difference if the function parameters were, for example, reference types (triggering the special rules in [14.8.2.4] in the case of a function call, but not in the other cases), but such forms can't occur with function templates generated from class template specializations.

So, this whole detour didn't help us one bit, but... it's a language-lawyer question, we had to have some standard quotes in here...


There are some active Core issues related to your example:

  • 1157 contains a note that I think is relevant:

    Template argument deduction is an attempt to match a P and a deduced A; however, template argument deduction is not specified to fail if the P and the deduced A are incompatible. This may occur in the presence of non-deduced contexts. Notwithstanding the parenthetical statement in 14.8.2.4 [temp.deduct.partial] paragraph 9, template argument deduction may succeed in determining a template argument for every template parameter while producing a deduced A that is not compatible with the corresponding P.

    I'm not entirely sure that's so clearly specified; after all, [14.8.2.5p1] says

    [...] find template argument values [...] that will make P, after substitution of the deduced values [...], compatible with A.

    and [14.8.2.4] references [14.8.2.5] in its entirety. However, it's pretty clear that partial ordering of function templates doesn't look for compatibility when non-deduced contexts are involved, and changing that would break a lot of valid cases, so I think this is just a lack of proper specification in the standard.

  • To a lesser extent, 1847 has to do with non-deduced contexts appearing in arguments to template specializations. It references 1391 for the resolution; I think there are some issues with that wording - more details in this answer.

To me, all of this says that your example should work.


Like you, I was quite intrigued by the fact that the same inconsistency is present in three different compilers. I got even more intrigued after I verified that MSVC 14 exhibits the exact same behaviour as the others. So, when I got some time, I thought I'd take a quick look at what Clang does; it turned out to be anything but quick, but it yielded some answers.

All the code relevant to our case is in lib/Sema/SemaTemplateDeduction.cpp.

The core of the deduction algorithm is the DeduceTemplateArgumentsByTypeMatch function; all variants of deduction end up calling it, and it's then used recursively to walk through the structure of compound types, sometimes with the help of the heavily overloaded DeduceTemplateArguments set of functions, and some flags to adjust the algorithm based on the specific type of deduction being done and the parts of a type's form being looked at.

An important aspect to note regarding this function is that it handles strictly deduction, and not substitution. It compares type forms, deduces template argument values for template parameters that appear in deduced contexts, and skips non-deduced contexts. The only other check it does is verifying that deduced argument values for a template parameter are consistent. I've written some more about the way Clang does deduction during partial ordering in the answer I mentioned above.

For partial ordering of function templates, the algorithm starts in the Sema::getMoreSpecializedTemplate member function, which uses a flag of type enum TPOC to determine the context for which partial ordering is being done; the enumerators are TPOC_Call, TPOC_Conversion, and TPOC_Other; self-explanatory. This function then calls isAtLeastAsSpecializedAs twice, back and forth between the two templates, and compares the results.

isAtLeastAsSpecializedAs switches on the value of the TPOC flag, makes some adjustments based on that, and ends up calling, directly or indirectly, DeduceTemplateArgumentsByTypeMatch. If that returns Sema::TDK_Success, isAtLeastAsSpecializedAs does only one more check, to verify that all template parameters that are used for partial ordering have values. If that's good too, it returns true.

And that's partial ordering for function templates. Based on the paragraphs quoted in the previous section, I was expecting partial ordering for class template specializations to call Sema::getMoreSpecializedTemplate with suitably constructed function templates and a flag of TPOC_Other, and everything to flow naturally from there. If that were the case, your example should work. Surprise: that's not what happens.

Partial ordering for class template specializations starts in Sema::getMoreSpecializedPartialSpecialization. As an optimization (red flag!), it doesn't synthesize function templates, but rather uses DeduceTemplateArgumentsByTypeMatch to do type deduction directly on the class template specializations themselves as the types of P and A. This is fine; after all, that's what the algorithm for function templates would end up doing anyway.

However, if all goes well during deduction, it then calls FinishTemplateArgumentDeduction (the overload for class template specializations), which does substitution and other checks, including checking that the substituted arguments to the specialization are equivalent to the original ones. This would be fine if the code were checking whether a partial specialization matches a set of arguments, but is not fine during partial ordering, and, as far as I can tell, causes the problem with your example.

So, it seems that Richard Corden's assumption as to what happens is correct, but I'm not entirely sure this was intentional. This looks more like an oversight to me. How we ended up with all compilers behaving the same way remains a mystery.

In my opinion, removing the two calls to FinishTemplateArgumentDeduction from Sema::getMoreSpecializedPartialSpecialization would do no harm, and would restore consistency to the partial ordering algorithm. There's no need for the additional check (done by isAtLeastAsSpecializedAs) that all template parameters have values either, as we know all template parameters are deducible from the specialization's arguments; if they weren't, the partial specialization would fail matching, so we wouldn't get to partial ordering in the first place. (Whether such partial specializations are allowed in the first place is the subject of issue 549. Clang issues a warning for such cases, MSVC and GCC issue an error. Anyway, not a problem.)

As a side note, I think all of this applies to the overload for variable template specializations as well.

Unfortunately, I don't have a build environment set up for Clang, so I can't test this change at the moment.

like image 123
bogdan Avatar answered Nov 03 '22 17:11

bogdan