Default template arguments

My understanding is default template arguments must be followed by default template arguments, should be not legal, but it compiles jut fine with msvc:

1
2
template<typename T = int, typename U>
T func(U param) { }


Am I missing something?

According to cpp reference:
If the default is specified for a template parameter of a primary class template, primary variable template, (since C++14) or alias template, each subsequent template parameter must have a default argument, except the very last one may be a template parameter pack.

https://en.cppreference.com/w/cpp/language/template_parameters

and according to IBM:
If one template parameter has a default argument, then all template parameters following it must also have default arguments.

https://www.ibm.com/docs/en/zos/2.1.0?topic=parameters-default-arguments-template

edit:

To get around this, with new c++20 feature, is the following a legal workaround?

1
2
template<typename T = int>
T func(auto param) {}


Basically I want return type to be first template parameter (and default) because type deduction for function parameter should be deducted, while return type should be either default or explicitly written if default is not desired, ex:

1
2
3
4
5
func (3); //return type is int

// or ...

func<float>(4); // return type is float 


in both cases there is never a need to write both parameters:
func<int, float>(2.f);
Last edited on
The quoted statement from cppreference does not apply to function templates. The very next sentence reads:
In a function template, there are no restrictions on the parameters that follow a default, and a parameter pack may be followed by more type parameters only if they have defaults or can be deduced from the function arguments.
Last edited on
Ah OK, I misread that part, this answers the abbreviated version as well then. thanks!
Topic archived. No new replies allowed.