VOOZH about

URL: https://www.geeksforgeeks.org/cpp/class-template-argument-deduction-in-cpp-17/

⇱ Class Template Argument Deduction in C++17 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Class Template Argument Deduction in C++17

Last Updated : 28 Apr, 2025

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.

Implicitly-Generated Deduction Guides

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.

Example


Output

Created MyContainer<i> with value: 42
Created MyContainer<PKc> with value: Hello

User-Defined Deduction Guides

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.

Example


Output

Created MyContainer<i> with value: 42
Created MyContainer<PKc> with value: Hello

Deduction for Alias Templates

The deduction for alias templates allows you to deduce the template arguments for an alias template based on its underlying type or value.

Example 1


Output

alias1: 42
alias2: A

Example 2

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.

Advantages of Class Template Argument Deduction

The advantages of using the Class Template Argument Deduction are:

  • It improves the complexity of the code
  • It reduces human error from the code
  • It increases the flexibility of the code when you use the template in multiple different types of code
  • It increases the performance as it has generosity and fewer lines of code.
Comment
Article Tags:
Article Tags: