Home > Article > Backend Development > Why Is It Necessary to Use Empty Angle Brackets for Class Templates with Default Arguments in C 11 and Earlier?
Understanding Template Arguments and Default Templates
In C , template arguments are an essential aspect of working with class and function templates. When declaring a class template with default template arguments, we can omit specifying the argument when creating an object, but this behavior is subject to certain limitations.
To illustrate, let's examine the following code:
<code class="cpp">template <typename T = int> class Foo { };</code>
This code defines a class template Foo with a default template argument of T = int. While we can create an object of Foo without explicitly specifying the template argument:
<code class="cpp">Foo me;</code>
it's important to note that this syntax was only introduced in C 17. Prior to that, the following code was required:
<code class="cpp">Foo<> me;</code>
The angle brackets (<>) indicate that the template arguments are present but empty. This syntax is necessary because the compiler needs to know the type of T, even when it's using the default value. Failure to provide the template arguments, as in Foo me;, would result in a compilation error.
This distinction is analogous to a function with a single default argument. Just as foo without parentheses won't call the function, but foo() will, the template argument syntax must be present to trigger instantiation with the default value.
The above is the detailed content of Why Is It Necessary to Use Empty Angle Brackets for Class Templates with Default Arguments in C 11 and Earlier?. For more information, please follow other related articles on the PHP Chinese website!