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
C++
// C++ program to demonstrate the usage of the deduction for // alias templates: #include <iostream> template < typename T> using MyAlias = T; int main() { MyAlias< int > alias1 = 42; MyAlias< char > alias2 = 'A' ; std::cout << "alias1: " << alias1 << std::endl; std::cout << "alias2: " << alias2 << std::endl; return 0; } |
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.
C++
// C++ program to illustrate the class template argument deduction #include <iostream> #include <vector> using namespace std; // Define a class template called MyContainer template < typename T> class MyContainer { private : vector<T> vec; // Private member variable of type vector public : // Constructor of MyContainer class that takes an // initializer list MyContainer( const initializer_list<T>& list) : vec(list) { } // Print function to display the elements of the vector void print() const { for ( const auto & val : vec) { cout << val << " " ; } cout << endl; } }; int main() { // Create an instance of MyContainer using class // template argument deduction // introduced in C++17 auto myContainer = MyContainer({ 1, 2, 3, 4, 5 }); // Print the elements of the container using the print() // function myContainer.print(); return 0; } |
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.
Class Template Argument Deduction in C++17
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.
Contact Us