Home  >  Article  >  Backend Development  >  Why Can't Template Type Parameters Be Deduced from Default Function Arguments in C ?

Why Can't Template Type Parameters Be Deduced from Default Function Arguments in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 00:24:02604browse

Why Can't Template Type Parameters Be Deduced from Default Function Arguments in C  ?

Why Template Type Parameters Cannot Be Deducted from Default Function Arguments

In C , a common misconception is that the compiler can deduce template type parameters from default function arguments. However, this is not the case.

When encountering the following code:

<code class="cpp">struct foo {
  template <typename T>
  void bar(int a, T b = 0.0f) {
  }
};

int main() {
  foo a;
  a.bar(5);  // Error: could not deduce template argument for T
}</code>

the compiler fails to deduce the type T from the default argument 0.0f. Instead, it requires explicit specification, as in a.bar(5).

C 03 Prohibition

In C 03, the language specification explicitly prohibits using default function arguments for template argument deduction (C 03 §14.8.2/17):

A template type-parameter cannot be deduced from the type of a function default argument.

C 11 Default Template Arguments

In C 11, a workaround emerged: introducing default template arguments. By modifying the code as follows:

<code class="cpp">template <typename T = float>
void bar(int a, T b = 0.0f) { }</code>

the default template parameter T is provided. However, it should be noted that having a default template argument does not alleviate the restriction on default function arguments.

According to C 11 14.8.2.5/5, default function arguments are considered "non-deduced contexts" in the template argument deduction process. This means that the compiler cannot use the default value from the function argument to infer the template type parameter.

Conclusion

While default function arguments provide convenience, template type parameters should not be inferred from them. For cases where default values are necessary, default template arguments offer a more portable and flexible solution.

The above is the detailed content of Why Can't Template Type Parameters Be Deduced from Default Function 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