liveBook · Manning

Class template argument deduction

As explained in Learn C++ by Example

Class template argument deduction is a C++ feature that deduces template arguments from a class template's construction arguments.

Class template argument deduction (CTAD) lets C++17 infer a class template’s arguments from construction arguments, reducing repeated type spelling. For example, std::vector data{ 1 } deduces a vector of integers. section 2.1

Use CTAD when the construction arguments provide enough information:

  • Write std::vector data{ 1 } instead of spelling std::vector<int>. section 2.1
  • Write std::pair two_words{"Hello,"s, "world!"s}; to deduce a pair of strings. section 7.1.2
  • Write std::tuple three_numbers{ 1, 1.23, 4.5f }; to deduce int, double, and float elements. section 7.1.2
  • Do not expect auto data = std::vector{} to work: an empty vector supplies no element type to deduce. section 2.1

A small container experiment

Start with std::vector<int> data{ 1 } and display its first value. Then replace the declaration with std::vector data{ 1 }; the behavior stays the same while CTAD removes the explicit element type. Compile, modify the initializer, and observe which types can be inferred. section 2.1

Listing 2.1 Filling and displaying a container
#include <iostream>                 #1
#include <vector>                   #1
 
void generate_triangle()
{
    std::vector<int> data{ 1 };     #2
    for (auto number : data)        #3
    {
        std::cout << number << ' ';
    }
    std::cout << '\n';
}
 
int main()
{
    generate_triangle();
}

The complete vector example shows the explicit form that CTAD can shorten, alongside initialization and range-based iteration. section 2.1

How Learn C++ by Example covers it

How deep it goes
Defines deduction through vector, pair, and tuple examples, but does not detail deduction guides or compiler rules.
Examples
Uses vectors initialized with integers, pairs of strings or mixed numbers, and tuples containing heterogeneous numeric values.
What it assumes
Assumes basic C++ initialization and templates while reinforcing type inference through concrete standard-library examples.
What you can do after
Apply CTAD to construct vectors, pairs, and tuples while recognizing when empty containers lack enough information.
How it connects
Connects CTAD with auto, initializer lists, standard containers, std::pair, std::tuple, and structured bindings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.