cpp17 · medium

C++17: Class Template Argument Deduction (CTAD)

Class Template Argument Deduction (C++17) lets the compiler deduce a class template's arguments from its constructor call, just as function templates always deduced theirs — so std::pair p{1, s} yields pair<int, string> and std::lock_guard g{mtx} yields lock_guard<mutex>, retiring make_pair/make_tuple-style helpers. When the constructor does not make the intended type clear, deduction guides (many provided by the standard library, e.g. iterator-pair and initializer_list guides; or user-written as ClassName(args) -> ClassName<T>;) steer the deduction. Gotchas for interviews: CTAD is all-or-nothing — you cannot specify some template arguments and deduce the rest — and a bare string literal deduces const char* rather than std::string, so be explicit when you need a string. make_shared/make_unique remain useful because they do more than deduce a type.

🔑 Key line

C++17 CTAD: the compiler deduces a class template's parameters from its constructor arguments (std::pair p{1,s} -> pair<int,string>), retiring most make_ helpers; it's all-or-nothing and deduction guides steer ambiguous cases.

The code

// pre-C++17: spell out the type, or use a make_ helper
std::pair<int, std::string> p1{1, "a"};
auto p2 = std::make_pair(1, std::string("a"));
// C++17: the class template args are deduced from the initializer
std::pair p{1, std::string("a")}; // -> pair<int, string>
std::vector v{1, 2, 3}; // -> vector<int>
std::lock_guard g{mtx}; // -> lock_guard<mutex>
std::tuple t{1, 'c', 3.0}; // -> tuple<int,char,double>

What this lesson walks through

  1. 01Templates deduce like functions now
  2. 02Deduction guides
  3. 03Gotcha — CTAD picks surprising types
  4. 04Gotchas & interview points

Before C++17, function templates deduced their arguments but class templates did not — hence make_pair, make_tuple, make_unique as workarounds. CTAD lets the compiler deduce a class template's arguments from the constructor call, so std::pair p{1, s} just works and yields pair<int, string>.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of C++17: Class Template Argument Deduction (CTAD) and 100+ animated C++ interview lessons.

← Previous
C++17: if constexpr
Next →
C++17: Fold Expressions