Loading lessons...
CTAD and Alias Templates
CTAD and Alias Templates
Two features that make templates friendlier to write: class template argument deduction (CTAD) and alias templates.
CTAD avoids typing
Before C++17 you often spelled every template argument:
std::pair<int, double> p{1, 2.5};
Since C++17, CTAD lets the compiler deduce those arguments from the values:
std::pair p {1, 2}; // deduced as std::pair<int, int>
No type appears in the brackets; the compiler reads the 1 and 2 and works the types out.
Alias templates
An alias template is a short name assigned to a longer template:
template <typename T>
using IntVec = std::vector<T>;
Now IntVec<int> means the same as std::vector<int>:
IntVec<int> scores; // a vector of ints
std::vector<int> also; // same exact type
Aliases keep long, nested type names short and readable.
TL;DR
- CTAD lets the compiler deduce class template arguments from the values.
std::pair p{1,2};is CTAD in action in C++17 and later.- Use
template <typename T> using Name = Other<T>;for an alias template. IntVec<int>is just another way to writestd::vector<int>.