Template Argument Deduction for Class Templates: Limitations and Implications
In the wake of the P0091 proposal to unify template argument deduction behavior for function and class templates, a question arises: why is partial class template argument deduction not possible?
The initial proposal aimed to align the deduction mechanisms, allowing for partial deduction in both contexts. However, concerns emerged regarding potential confusion when the deduced values produce multiple valid template specializations. A classic example is the deduction of a tuple type: by specifying only one argument, the compiler could infer a tuple with a single element, even though the original tuple definition includes multiple elements.
To prevent such ambiguity, partial class template argument deduction was removed from the proposal. This limitation affects scenarios where developers may wish to explicitly specify certain template parameters while leaving others to be deduced.
For instance, consider the following class template:
template <std::size_t S, typename T> struct test { static constexpr auto size = S; using type_t = T; test(type_t (&input)[size]) : data(input) {} type_t (&data)[size]{}; };
A helper function serves as a syntactic sugar for instantiating test objects:
template <std::size_t S, typename T> test<S, T> helper(T (&input)[S]) { return input; }
When using the helper with a pre-declared array:
int buffer[5]; auto a = helper<5, int>(buffer); // No deduction auto b = helper<5>(buffer); // Type deduced auto c = helper(buffer); // Type and size deduced
Partial deduction is not supported in the case of class templates, as evidenced by the failure of auto b = helper<5>(buffer);. The compiler cannot infer the T parameter from the argument, leading to a compilation error. Instead, auto c = helper(buffer); successfully deduces both S and T, demonstrating the necessity of specifying all template parameters explicitly.
The above is the detailed content of Why is Partial Class Template Argument Deduction Not Possible?. For more information, please follow other related articles on the PHP Chinese website!