Home >Backend Development >C++ >Why Can't C Deduce 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!