Previous efforts to introduce template argument deduction for class templates aimed to align their behavior with that of function templates. However, the release of the P0091 proposal brought to light a key limitation: partial class template argument deduction remains impossible.
Consider the example provided, where a class template test is defined. The helper function helper simplifies the creation of test objects, as evident in the code snippet where various forms of argument deduction are demonstrated.
While the code compiles in most cases, difficulties arise when attempting partial deduction for class templates. For instance, line 6 of the following code fails to compile:
int buffer[5]; test<5> b(buffer); // Type deduced: FAILS.
This occurs because the compiler is unable to determine the type parameter T. Without explicit specification, the compiler expects all template arguments to be deduced simultaneously. This poses a challenge, as each parameter's deduction process can impact the deduction of others.
The report by Botond Ballo highlights the rationale behind this limitation:
The feature as originally proposed included a provision for partial deduction, where you explicitly specify some of the template arguments, and leave the rest to be deduced, but this was pulled over concerns that it can be very confusing in some cases:
// Would have deduced tuple<int, string, float>, // but tuple<int> is a well-formed type in and of itself! tuple<int> t(42, "waldo", 2.0f);Copy after login
Thus, while function templates allow for partial argument deduction, the ambiguity introduced by partial deduction in class templates led to its exclusion.
The above is the detailed content of Why Can't We Have Partial Class Template Argument Deduction?. For more information, please follow other related articles on the PHP Chinese website!