Home >Backend Development >C++ >Why Can't C Deduce Template Parameters from Default Function Arguments?

Why Can't C Deduce Template Parameters from Default Function Arguments?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 08:07:02392browse

Why Can't C   Deduce Template Parameters from Default Function Arguments?

Deducing Template Parameters from Default Function Arguments

The inability of the compiler to deduce template arguments from default function arguments in the provided code can be attributed to stipulations of the C language specification.

In C 03, as cited in §14.8.2/17 of the specification, "A template type-parameter cannot be deduced from the type of a function default argument." This restriction explicitly prohibits the use of default arguments for template parameter deduction.

While C 11 introduced the possibility of specifying default template arguments for function templates, the default function argument is still not usable for template argument deduction. Specifically, C 11 §14.8.2.5/5 states that "The non-deduced contexts are: ... A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done."

Therefore, the provided code's inability to deduce the template parameter for T from the default argument 0.0f is consistent with the language specification. To resolve the issue, an explicit template argument must be provided when calling the bar function, as demonstrated in the following revised code:

a.bar<float>(5);

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