![]() |
VOOZH | about |
In this article, we will learn about Class Template Argument Deduction(CTAD) in C++17 and with examples. CTAD is a feature in C++17 that allows the template arguments to be deduced from constructor arguments. In simple words, we can say that instead of explicitly specifying the template arguments the compiler can automatically deduce them based on the constructor arguments.
When a class template has a constructor that uses each template parameter in its parameter list, the compiler can generate an implicit deduction guide for that class template. This deduction guide allows the class template to be instantiated without explicitly providing template arguments.
Output
Created MyContainer<i> with value: 42 Created MyContainer<PKc> with value: Hello
User-defined deduction guides allow you to provide custom rules for class template argument deduction. These guides help the compiler deduce the template arguments based on the constructor arguments.
Output
Created MyContainer<i> with value: 42 Created MyContainer<PKc> with value: Hello
The deduction for alias templates allows you to deduce the template arguments for an alias template based on its underlying type or value.
Output
alias1: 42 alias2: A
In the below code, we will make use of the above syntax to demonstrate the use of the Class Template Argument Deduction in C++17.
Output
1 2 3 4 5
Note: Just like class templates, the arguments of function templates can also be automatically deduced and this feature has been the part of standard C++ since much earlier that Class Template Argument Deduction.
The advantages of using the Class Template Argument Deduction are: