Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default template parameter before deduced parameter in a function?

The following compile with no problem in g++ :

template<typename ReturnType = double, typename OtherType> ReturnType func(const OtherType& var)
{
    ReturnType result = 0;
    /* SOMETHING */
    return result;
}

Is it ok for all standard-compliant compilers to have a not-defaulted template parameter (OtherType here) after a defaulted template parameter (ReturnType here) ?

like image 856
Vincent Avatar asked Aug 20 '12 23:08

Vincent


People also ask

Can template have default parameters?

Template parameters may have default arguments. The set of default template arguments accumulates over all declarations of a given template.

Why do we use template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

What is a template template parameter in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What are template parameters?

In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.


1 Answers

It's complicated. From the C++11 spec:

If a template-parameter of a class template has a default template-argument, each subsequent template- parameter shall either have a default template-argument supplied or be a template parameter pack. If a template-parameter of a primary class template is a template parameter pack, it shall be the last template- parameter . [ Note: These are not requirements for function templates or class template partial specializations because template arguments can be deduced (14.8.2).

So what you're trying to do is not allowed for classes, unless it's a partial specialization. But for functions it's ok.

So as long as you're only doing this trick with functions as you show in your example, it's ok. You just can't generalize that to class templates.

like image 109
Lily Ballard Avatar answered Sep 20 '22 01:09

Lily Ballard