Template Argument Deduction from Default Function Arguments
In C , programmers often encounter scenarios where they need to deduce template arguments from function calls. However, there might be cases where this deduction fails, leading to compiler errors. One such case is the inability to deduce template type parameters from default function arguments.
Consider the following code snippet:
<code class="cpp">struct foo { template <typename T> void bar(int a, T b = 0.0f) { } }; int main() { foo a; a.bar(5); }</code>
Upon compiling this code, the compiler might generate an error stating, "could not deduce template argument for T." To resolve this issue, one needs to explicitly specify the template argument in the function call, such as a.bar
In C 03, the language specifications explicitly forbid the use of default arguments to deduce template arguments. According to C 03 §14.8.2/17, "A template type-parameter cannot be deduced from the type of a function default argument."
In C 11, the language introduced a new feature that allows providing default template arguments for function templates:
<code class="cpp">template <typename T = float> void bar(int a, T b = 0.0f) { }</code>
However, the default template argument is mandatory. If it is not provided, the compiler still prohibits the use of the default function argument for template argument deduction. C 11 §14.8.2.5/5 states that:
"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" is a non-deduced context.
In summary, while providing default arguments for function parameters can simplify code, it is essential to understand the limitations of template argument deduction in such cases. Default arguments can only be used for template argument deduction if a default template argument is explicitly provided.
The above is the detailed content of Why Can't C Deduce Template Arguments from Default Function Arguments?. For more information, please follow other related articles on the PHP Chinese website!