Home  >  Article  >  Backend Development  >  Why Can\'t Default Template Arguments Be Used for Member Function Templates in C ?

Why Can\'t Default Template Arguments Be Used for Member Function Templates in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 12:38:01895browse

Why Can't Default Template Arguments Be Used for Member Function Templates in C  ?

Default Template Arguments: Why Limited to Class Templates?

In C , default template arguments are only allowed for class templates. This restriction raises the question of why such arguments cannot be defined for member function templates.

Consider the following example:

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

In this example, an attempt is made to define a default type for the template parameter T within a member function template, but this syntax is not permitted by C . Instead, default template arguments are strictly limited to class templates.

Reasoning Behind the Restriction

The prohibition of default template arguments for function templates stems from historical reasons. In early versions of C , freestanding functions were not fully integrated into the language's template system. To encourage the use of member function templates, which were considered more idiomatic, default template arguments were restricted to class templates.

However, this restriction has since been recognized as a limitation, as it unnecessarily differentiates between member function templates and freestanding function templates. As pointed out by Bjarne Stroustrup in a defect report:

"The prohibition of default template arguments for function templates is a misbegotten remnant... [it] seriously cramps programming style by unnecessarily making freestanding functions different from member functions."

C 0x Update

In response to these concerns, C 0x introduced default template arguments for freestanding function templates. This change allows for more flexibility and consistency in template programming.

Example

Consider the following C 0x code:

<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>

In this example, a default template argument is specified for the Comp template parameter, allowing the sorting algorithm to use the standard less comparison function by default.

The above is the detailed content of Why Can\'t Default Template Arguments Be Used for Member Function 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