Home > Article > Backend Development > Why are Default Template Arguments Restricted to Class Templates in C ?
In C , default template arguments are only allowed on class templates but not on function templates. This restriction may seem surprising, but there are several reasons behind it.
Default template arguments allow class templates to provide a default value for certain parameters. This can be useful when the default value is unlikely to change for most instances of the template. For example, a class template for a sorting algorithm could have a default template argument for the comparison function used in sorting.
However, default template arguments are not allowed for function templates because they would introduce ambiguity. Consider the following hypothetical example:
<code class="cpp">struct my_class { template<class T = int> void mymember(T* vec) { // ... } };</code>
In this example, it would be unclear whether T is the default type for the mymember function or for the my_class template itself. This ambiguity could lead to subtle errors in the code.
Prior to C 11, the prohibition of default template arguments for function templates was a significant limitation. However, C 11 introduced a new feature called "type aliases" which allows us to define aliases for types. This provides a workaround for the lack of default template arguments for function templates. For example, the example above could be rewritten as follows:
<code class="cpp">struct my_class { typedef int default_type; template<class T = default_type> void mymember(T* vec) { // ... } };</code>
While type aliases are not as convenient as default template arguments, they provide a similar functionality and allow us to overcome the limitations of the current C standard.
In a defect report, Bjarne Stroustrup, the original designer of C , expressed his view on the prohibition of default template arguments for function templates:
The prohibition of default template arguments for function templates is a misbegotten remnant of the time where freestanding functions were treated as second class citizens and required all template arguments to be deduced from the function arguments rather than specified.
The above is the detailed content of Why are Default Template Arguments Restricted to Class Templates in C ?. For more information, please follow other related articles on the PHP Chinese website!