Home > Article > Backend Development > Why Can't C Compilers Deduce Template Type Parameters from Default Function Arguments?
Why Can't Compilers Deduct Template Type Parameters from Default Function Arguments?
Despite the seemingly logical assumption, C compilers cannot automatically infer template type parameters from default function arguments. This holds true both in C 03 and C 11, for distinct reasons.
In C 03, the compiler's inability stems from explicit language specifications (§14.8.2/17): "A template type-parameter cannot be deduced from the type of a function default argument."
In C 11, while it is possible to specify a default template argument, it must be provided explicitly. The default function argument itself remains unusable for template argument deduction:
<code class="cpp">void bar(int a, T b = 0.0f) { } // C++11</code>
The C 11 standard (14.8.2.5/5) defines non-deduced contexts, which include:
As a result, the explicit provision of default template arguments is often necessary to avoid compilation errors.
The above is the detailed content of Why Can't C Compilers Deduce Template Type Parameters from Default Function Arguments?. For more information, please follow other related articles on the PHP Chinese website!