Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-31 02:14:01
Original
757 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!