Home  >  Article  >  Backend Development  >  Why Do I Still Need to Specify Arguments for a Class Template with Default Arguments?

Why Do I Still Need to Specify Arguments for a Class Template with Default Arguments?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 04:56:30823browse

Why Do I Still Need to Specify Arguments for a Class Template with Default Arguments?

Understanding Default Template Arguments in C : Avoiding Specified Arguments

In C programming, it is possible to declare a class template with default template arguments. However, it can be confusing to understand why specifying arguments is still required in certain scenarios.

Original Question:

Consider the following class template:

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

According to the question, the following code should be allowed:

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

However, instead, the following code is required:

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

Answer:

Prior to C 17, specifying arguments in a class template declaration with default arguments was mandatory. In other words, the following code was required:

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

Even though the template argument is not explicitly provided, the empty angle brackets < > must be present to indicate that the default argument is being used. This syntax is analogous to calling a function with a single default argument, which requires empty parentheses ().

C 17 Update:

In C 17, this behavior changed, and it became possible to omit the angle brackets <> when using the default template argument. Therefore, the following alternative syntax is now allowed:

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

Conclusion:

Understanding the requirement of specifying arguments in class templates with default arguments requires familiarity with the historical evolution of C . In pre-C 17 versions, explicit angle brackets <> were required, while C 17 introduced a more convenient syntax that allows for their omission when using the default argument.

The above is the detailed content of Why Do I Still Need to Specify Arguments for a Class Template with Default Arguments?. 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