C++ Deduction Guides | Customizing CTAD in C++17
이 글의 핵심
Deduction guides tell the compiler how to map constructor arguments to class template parameters—essential for polished CTAD on user-defined class templates.
What are deduction guides?
Deduction guides (C++17) customize CTAD—how the compiler deduces class template arguments from constructor arguments.
template<typename T>
class Container {
public:
Container(T value) {}
};
template<typename T>
Container(T) -> Container<T>;
Container c(42); // Container<int>
Why they matter
- Resolve ambiguous deduction between multiple constructors
- Perform type transformations (e.g.
const char*→std::string) - Improve API ergonomics
- Match STL-style usage patterns
template<typename T>
class Container {
public:
Container(const char* str) {}
};
Container(const char*) -> Container<std::string>;
Container c("hello"); // Container<std::string>
Basic syntax
template<typename T>
class MyClass {
public:
MyClass(T value) {}
};
template<typename T>
MyClass(T) -> MyClass<T>;
Practical examples
Array + size
template<typename T>
Array(T*, size_t) -> Array<T>;
Iterator range
template<typename Iter>
Vector(Iter, Iter) -> Vector<typename std::iterator_traits<Iter>::value_type>;
Smart pointer style
template<typename T>
SmartPtr(T*) -> SmartPtr<T>;
Pair-like with string conversion
Pair(const char*, const char*) -> Pair<std::string, std::string>;
Standard library
std::array, std::pair, std::tuple, std::optional, std::vector, etc. provide library guides so CTAD works as expected.
Pitfalls
Ambiguous deduction
Add a more specific guide or split constructors.
Duplicate / redundant guides
If implicit deduction already works, an extra identical guide may be unnecessary.
Copy constructor vs CTAD
Wrapper w2 = w1 vs Wrapper w3(w1) can deduce differently—sometimes you need:
template<typename T>
Wrapper(Wrapper<T>) -> Wrapper<T>;
explicit guides
template<typename T>
explicit Container(T) -> Container<T>;
Advanced patterns
Conditional result types, initializer_list targets, and iterator-range guides are common in real libraries.
FAQ
Q1: When are guides needed?
A: When CTAD’s default constructor-to-template mapping is wrong or ambiguous.
Q2: Are they always required?
A: No—many class templates deduce fine with the primary template alone.
Q3: Performance?
A: Compile-time only.
Q4: Do guides inherit?
A: No—define guides per class.
In one sentence: Deduction guides are the explicit “rules” that make CTAD predictable for your own templates.
Related posts
- CTAD
- Template argument deduction
- Template template parameters
Keywords
C++, deduction guide, CTAD, C++17, templates.
See also
if constexprstd::anyautodeduction