From this page on cppreference about default template arguments:
If the default is specified for a template parameter of a primary class template, [...] each subsequent template parameter must have a default argument, except the very last one may be a template parameter pack (since C++11). In a function template, there are no restrictions on the parameters that follow a default [...].
This means the following code compiles:
template <typename U = int, typename T>
U foo(T) { /*... */ }
while this doesn't:
template <typename U = int, typename T>
struct S {
S(T) { /* ... */ }
};
What's the reasoning behind this?
This kind of makes sense to me until C++17, as you had to specify T
(hence
U
) when constructing an instance of S
:
S<int, double> s(1.2);
However, C++17 introduced CTAD: couldn't the standard allow non defaulted template parameters after the last defaulted one as long as they're deducible from the initializer?
Note: I've already had a look at question "Non-last default template arguments for function templates" but it doesn't answer mine.