Partial Class Template Argument Deduction in C 17
The C 17 feature "Class Template Argument Deduction" (CTAD) allows compilers to automatically deduce the template arguments of a class when it is instantiated. This simplifies code and eliminates the need for specifying explicit template arguments.
However, can we partially specify template arguments and let the rest be deduced?
Attempted Solution 1:
One attempt to achieve partial deduction involves creating an alias template as follows:
<code class="cpp">template<class T, class U> using Base2 = Base<T, U, double>;</code>
Then use the alias to partially specify the arguments:
<code class="cpp">void func() { Base2 val(1, 2); }</code>
However, this will result in a compilation error, indicating that using an alias template requires a complete template argument list.
Workarounds:
Unfortunately, partial deduction is not directly supported in C 17. However, there are some workarounds available:
1. Overload Helper Functions:
Create overload functions with different sets of specified arguments and use the most specific overload for deduction:
<code class="cpp">template<class T, class U> void func(Base<T, U> val) { } template<class T> void func(Base<T, double> val) { } template<> void func(Base<double> val) { }</code>
2. Explicit Argument Deduction:
Use explicit template argument deduction to specify specific arguments while deducing the others:
<code class="cpp">Base val(1, static_cast<double>(4.), false);</code>
3. Utilize variadic templates:
Create a variadic template that accepts multiple arguments and can deduce the template arguments:
<code class="cpp">template<typename... Args> class Base { public: Base(Args&&... args) { // Custom logic to deduce template arguments from args... } };</code>
Conclusion:
Partial class template argument deduction is not directly supported in C 17. However, by using workarounds such as function overloading, explicit deduction, or variadic templates, it is possible to achieve a similar effect.
The above is the detailed content of ## Can We Partially Deduce Template Arguments for Class Templates in C 17?. For more information, please follow other related articles on the PHP Chinese website!