Home  >  Article  >  Backend Development  >  Why are Default Template Arguments Only Allowed for Class Templates in C ?

Why are Default Template Arguments Only Allowed for Class Templates in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 02:14:01757browse

Why are Default Template Arguments Only Allowed for Class Templates in C  ?

Default Template Arguments: Class Templates vs. Member Function Templates

Q: Why are default template arguments only permitted for class templates? Why not for member function templates as well?

Example:

<code class="cpp">struct my_class {
  template<class T = int>
  void mymember(T* vec) {
    // ...
  }
};</code>

According to C , default template arguments are only valid for class templates.

A: Default template arguments are indeed useful. Consider a sort function:

<code class="cpp">template<typename Iterator, 
         typename Comp = std::less<
            typename std::iterator_traits<Iterator>::value_type>>
void sort(Iterator beg, Iterator end, Comp c = Comp()) {
  ...
}</code>

However, the rationale for the current restriction in C is rooted in the early days of the language when freestanding functions were considered less important. Consequently, they were required to deduce all template arguments from function arguments, precluding the use of default values.

This limitation hampers code flexibility and compatibility with member function templates. To rectify this, C 0x introduced default template arguments for function templates.

As Bjarne Stroustrup, the creator of C , stated in a defect report:

"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 restriction seriously cramps programming style by unnecessarily making freestanding functions different from member functions, thus making it harder to write STL-style code."

The above is the detailed content of Why are Default Template Arguments Only Allowed for Class Templates in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn