Lesson 162 +10 XP

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:

Code

cpp
std::pair<int, double> p{1, 2.5};

Since C++17, CTAD lets the compiler deduce those arguments from the values:

Code

cpp
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:

Code

cpp
template <typename T>
using IntVec = std::vector<T>;

Now IntVec&lt;int&gt; means the same as std::vector&lt;int&gt;:

Code

cpp

### 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 &lt;typename T&gt; using Name = Other&lt;T&gt;; for an alias template.
  • IntVec&lt;int&gt; is just another way to write std::vector&lt;int&gt;.