@@ -49,6 +49,7 @@ C++17 includes the following new language features:
4949- [ direct-list-initialization of enums] ( #direct-list-initialization-of-enums )
5050- [ \[\[ fallthrough\]\] , \[\[ nodiscard\]\] , \[\[ maybe_unused\]\] attributes] ( #fallthrough-nodiscard-maybe_unused-attributes )
5151- [ \_\_ has\_ include] ( #\_\_ has\_ include )
52+ - [ class template argument deduction] ( #class-template-argument-deduction )
5253
5354C++17 includes the following new library features:
5455- [ std::variant] ( #stdvariant )
@@ -1024,6 +1025,39 @@ It can also be used to include headers existing under different names or locatio
10241025#endif
10251026```
10261027
1028+ ### Class template argument deduction
1029+ * Class template argument deduction* (CTAD) allows the compiler to deduce template arguments from constructor arguments.
1030+ ``` c++
1031+ std::vector v{ 1, 2, 3 }; // deduces std::vector<int >
1032+
1033+ std::mutex mtx;
1034+ auto lck = std::lock_guard{ mtx }; // deduces to std::lock_guard< std::mutex >
1035+
1036+ auto p = new std::pair{ 1.0, 2.0 }; // deduces to std::pair<double, double>
1037+ ```
1038+
1039+ For user-defined types, *deduction guides* can be used to guide the compiler how to deduce template arguments if applicable:
1040+ ```c++
1041+ template <typename T>
1042+ struct container {
1043+ container(T t) {}
1044+
1045+ template <typename Iter>
1046+ container(Iter beg, Iter end);
1047+ };
1048+
1049+ // deduction guide
1050+ template <template Iter>
1051+ container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>;
1052+
1053+ container a{ 7 }; // OK: deduces container<int>
1054+
1055+ std::vector<double> v{ 1.0, 2.0, 3.0 };
1056+ auto b = container{ v.begin(), v.end() }; // OK: deduces container<double>
1057+
1058+ container c{ 5, 6 }; // ERROR: std::iterator_traits<int>::value_type is not a type
1059+ ```
1060+
10271061## C++17 Library Features
10281062
10291063### std::variant
0 commit comments