C++ - Class template argument deduction guide
A deduction guide tells the compiler how to deduce template arguments when you construct an object without explicitly specifying them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
template <typename T>
struct Box {
T value;
Box(T v) : value(v) {}
};
// Deduction guide
Box(const char*) -> Box<std::string>;
int main() {
Box b1(42); // deduces Box<int>
Box b2("hello"); // normally deduces Box<const char*>
// but deduction guide forces -> Box<std::string>
std::cout << b1.value << "\n"; // 42
std::cout << b2.value << "\n"; // hello
}
✅ Without the guide, “hello” would make a Box<const char*>.
✅ With the guide, the compiler redirects deduction to Box<std::string>.