Home > Backend Development > C++ > body text

Why is Partial Class Template Argument Deduction Not Possible?

Barbara Streisand
Release: 2024-11-09 01:02:01
Original
814 people have browsed it

Why is Partial Class Template Argument Deduction Not Possible?

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 (&amp;input)[size]) : data(input) {}
    type_t (&amp;data)[size]{};
};
Copy after login

A helper function serves as a syntactic sugar for instantiating test objects:

template <std::size_t S, typename T>
test<S, T> helper(T (&amp;input)[S]) { return input; }
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template