Home  >  Article  >  Backend Development  >  Why Do I Still Need to Specify Template Arguments When Using Default Template Arguments in C ?

Why Do I Still Need to Specify Template Arguments When Using Default Template Arguments in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 17:21:01244browse

Why Do I Still Need to Specify Template Arguments When Using Default Template Arguments in C  ?

Understanding the Use of Default Template Arguments in C

Question:

Despite being able to define a class template with default template arguments, as seen below:

<code class="cpp">template <typename T = int>
class Foo {
};</code>

Why is it necessary to specify template arguments when instantiating the class in the following example?

<code class="cpp">Foo<int> me;</code>

Answer:

Contrary to what the question suggests, it is not necessary to explicitly specify template arguments when defining a class template with default template arguments. As of C 17, the following code is valid:

<code class="cpp">Foo me;</code>

Prior to C 17, however, the following syntax was required:

<code class="cpp">Foo<> me;</code>

This means that the template arguments must be present even if they are empty. This behavior is analogous to calling a function with a single default argument, where both foo() and foo without arguments are valid expressions, but only the former will call the function.

By introducing default template arguments, C 11 made it easier to work with class templates by providing a way to set default values for template parameters. Additionally, as demonstrated by the change in behavior between C 11 and C 17, this syntax has evolved over time to improve usability.

The above is the detailed content of Why Do I Still Need to Specify Template Arguments When Using Default Template Arguments 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