Partial Template Argument Deduction in C 17
Class Template Argument Deduction (CTAD) was introduced in C 17, allowing the compiler to automatically deduce template arguments based on the types of function arguments. However, CTAD currently requires all template arguments to be deduced or explicitly specified. Is it possible to partially specify template arguments and let the remaining ones be deduced?
Consider the following example:
<code class="cpp">template<class T, class U, class V> struct Base { constexpr Base(T, U) {} constexpr Base(T, U, V) {} constexpr Base(V) {} }; void func() { constexpr Base val(1, 4.0, false); }</code>
Using CTAD, the compiler will correctly deduce that val has the type Base
<code class="cpp"> constexpr Base<T = bool> val1(1, 4.0); // U & V deduced -> Base<int, double, bool> constexpr Base<T = bool, T = int> val2(5.0); // V deduced -> Base<bool, int, double></code>
Unfortunately, this code will not compile, as the compiler requires all template arguments to be either deduced or explicitly specified.
Workarounds
Since partial CTAD is not directly supported, there are a few workarounds we can use:
<code class="cpp">using NewBase2 = Base<double, int>; void func() { constexpr NewBase2 val(1, 2); }</code>
Conclusion
Partial CTAD is not directly supported in C 17, but there are workarounds available to achieve similar functionality. The upcoming C 20 standard is expected to include support for CTAD with alias templates, but it does not currently include support for partial CTAD or CTAD with inherited constructors.
The above is the detailed content of ## Can C 17 Partially Deduce Template Arguments in Class Template Argument Deduction (CTAD)?. For more information, please follow other related articles on the PHP Chinese website!