Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Class template argument deduction and deduction guides

CTAD lets you omit class template arguments when initializing an object. The compiler selects a specialization using candidates derived from constructors and deduction guides. A guide selects the type but does not replace a constructor.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

template<class T> struct Box { Box(T); };
template<class U> Box(U) -> Box<U>;
Box value{42};

CTAD / deduction guide refers to class template argument deduction and a guide that directs it. Writing Box a{3.5} omits <double>: the compiler determines the specialization from the initializer. This does not turn Box into an ordinary type without template arguments.

The compiler considers fictional function candidates, including those formed from constructors and declared guides, then applies deduction and overload resolution. In the example, the constructor Box(T) allows Box<double> to be deduced for a without a programmer-written guide.

The guide Box(int) -> Box<long>; selects Box<long> for b. A deduction guide must be declared in the same scope as the class template declaration. Here, that means declaring the guide alongside Box in the same namespace, not inside the definition of Box. The guide has no body and is not a constructor. Once the type is determined, the object must still be initializable. Here, the constructor of Box<long> receives the value 42 after conversion from int to long.

CTAD does not guarantee success: deduction can fail or selection can be ambiguous. Explicit arguments, such as Box<int>, bypass CTAD. This entry targets C++23 mode; the supplied sources are an evolving working draft, not frozen C++23 wording. Production runtime execution has not been attested.

Examples

#include <iostream>
#include <type_traits>

template<class T>
struct Box {
    T value;
    explicit Box(T x) : value(x) {}
};

Box(int) -> Box<long>;

int main() {
    Box a{3.5};
    Box b{42};
    static_assert(std::is_same_v<decltype(a), Box<double>>);
    static_assert(std::is_same_v<decltype(b), Box<long>>);
    std::cout << b.value << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources