类模板实参推导 (CTAD) (自 C++17 起)
为了实例化类模板,每个模板实参都必须是已知的,但并非每个模板实参都必须指定。在下列语境中,编译器将从初始化器的类型推导模板实参
std::pair p(2, 4.5); // deduces to std::pair<int, double> p(2, 4.5); std::tuple t(4, 3, 2.5); // same as auto t = std::make_tuple(4, 3, 2.5); std::less l; // same as std::less<void> l;
template<class T> struct A { A(T, T); }; auto y = new A{1, 2}; // allocated type is A<int>
- 函数式转型表达式
auto lck = std::lock_guard(mtx); // deduces to std::lock_guard<std::mutex> std::copy_n(vi1, 3, std::back_insert_iterator(vi2)); // deduces to std::back_insert_iterator<T>, // where T is the type of the container vi2 std::for_each(vi.begin(), vi.end(), Foo([&](int i) {...})); // deduces to Foo<T>, // where T is the unique lambda type
template<class T> struct X { constexpr X(T) {} }; template<X x> struct Y {}; Y<0> y; // OK, Y<X<int>(0)> |
(自 C++20 起) |
内容 |
[编辑] 类模板的推导
[编辑] 隐式生成的推导指引
当在函数式转型或变量声明中,类型说明符仅由主类模板 C
的名称组成(即,没有伴随的模板实参列表),则按如下方式形成推导候选项
- 若定义了
C
,则对于在已命名的主模板中声明的每个构造函数(或构造函数模板)Ci
,都构造一个虚构的函数模板Fi
,使得满足所有下列条件
Fi
的模板形参是C
的模板形参,后随(若Ci
是构造函数模板)Ci
的模板形参(也包括默认模板实参)。
|
(自 C++20 起) |
Fi
的形参列表是Ci
的形参列表。Fi
的返回类型是C
,后随花括号<>
中括起的类模板的模板形参。
- 若未定义
C
或它不声明任何构造函数,则添加额外的虚构函数模板,如上所述从假想的构造函数C()
导出。
- 在任何情况下,都添加额外的虚构函数模板,如上所述从假想的构造函数
C(C)
导出,称作复制推导候选项。
- 对于每个用户定义的推导指引
Gi
,都构造一个虚构函数或函数模板Fi
,使得满足所有下列条件
Fi
的形参列表是Gi
的形参列表。Fi
的返回类型是Gi
的简单模板标识符。- 若
Gi
拥有模板形参(语法 (2)),则Fi
是函数模板,且其模板形参列表是Gi
的模板形参列表。否则,Fi
是函数。
template<class T> struct A { T t; struct { long a, b; } u; }; A a{1, 2, 3}; // aggregate deduction candidate: // template<class T> // A<T> F(T, long, long); template<class... Args> struct B : std::tuple<Args...>, Args... {}; B b{std::tuple<std::any, std::string>{}, std::any{}}; // aggregate deduction candidate: // template<class... Args> // B<Args...> F(std::tuple<Args...>, Args...); // type of b is deduced as B<std::any, std::string> |
(自 C++20 起) |
然后为假想类类型的虚构对象的初始化执行模板实参推导和重载决议,该假想类类型的构造函数签名匹配指引(返回类型除外),并且初始化器由执行类模板实参推导的语境提供,但如果初始化器列表由类型为(可能为 cv 限定)U
的单表达式组成,其中 U
是 C
的特化或从 C
的特化派生的类,则省略列表初始化的第一阶段(考虑初始化器列表构造函数)。
这些虚构构造函数是假想类类型的公开成员。若指引从显式构造函数形成,则它们为显式的。若重载决议失败,则程序为谬构。否则,选定的 F
模板特化的返回类型变成推导的类模板特化。
template<class T> struct UniquePtr { UniquePtr(T* t); }; UniquePtr dp{new auto(2.0)}; // One declared constructor: // C1: UniquePtr(T*); // Set of implicitly-generated deduction guides: // F1: template<class T> // UniquePtr<T> F(T* p); // F2: template<class T> // UniquePtr<T> F(UniquePtr<T>); // copy deduction candidate // imaginary class to initialize: // struct X // { // template<class T> // X(T* p); // from F1 // // template<class T> // X(UniquePtr<T>); // from F2 // }; // direct-initialization of an X object // with "new double(2.0)" as the initializer // selects the constructor that corresponds to the guide F1 with T = double // For F1 with T=double, the return type is UniquePtr<double> // result: // UniquePtr<double> dp{new auto(2.0)}
或者,对于更复杂的例子(注意:“S::N
”将无法编译:作用域解析限定符不是可以推导的东西)
template<class T> struct S { template<class U> struct N { N(T); N(T, U); template<class V> N(V, U); }; }; S<int>::N x{2.0, 1}; // the implicitly-generated deduction guides are (note that T is already known to be int) // F1: template<class U> // S<int>::N<U> F(int); // F2: template<class U> // S<int>::N<U> F(int, U); // F3: template<class U, class V> // S<int>::N<U> F(V, U); // F4: template<class U> // S<int>::N<U> F(S<int>::N<U>); (copy deduction candidate) // Overload resolution for direct-list-init with "{2.0, 1}" as the initializer // chooses F3 with U=int and V=double. // The return type is S<int>::N<int> // result: // S<int>::N<int> x{2.0, 1};
[编辑] 用户定义的推导指引
用户定义的推导指引的语法是带有尾随返回类型的函数(模板)声明的语法,但它使用类模板的名称作为函数名
explicit (可选) 模板名 ( 形参列表 ) -> 简单模板 ID requires 子句 (可选) ; |
(1) | ||||||||
template < 模板形参列表 > requires 子句 (可选)explicit (可选) 模板名 ( 形参列表 ) -> 简单模板 ID requires 子句 (可选) ; |
(2) | ||||||||
模板形参列表 | - | 非空的逗号分隔的模板形参列表 |
explicit | - | explicit 说明符 |
模板名 | - | 要推导其形参的类模板的名称 |
形参列表 | - | (可能为空的)形参列表 |
简单模板 ID | - | 简单模板标识符 |
requires 子句 | - | (自 C++20 起) requires 子句 |
用户定义的推导指引的形参不能拥有占位符类型:不允许使用缩略函数模板语法。 |
(自 C++20 起) |
用户定义的推导指引必须命名一个类模板,且必须在类模板的同一语义作用域(可以是命名空间或外围类)内引入,对于成员类模板,必须拥有相同的访问权限,但推导指引不成为该作用域的成员。
推导指引不是函数,且不拥有函数体。推导指引不通过名字查找找到,且不参与重载决议,除了在推导类模板实参时,针对其他推导指引的重载决议。对于同一类模板,推导指引不能在同一翻译单元中重新声明。
// declaration of the template template<class T> struct container { container(T t) {} template<class Iter> container(Iter beg, Iter end); }; // additional deduction guide template<class Iter> container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>; // uses container c(7); // OK: deduces T=int using an implicitly-generated guide std::vector<double> v = {/* ... */}; auto d = container(v.begin(), v.end()); // OK: deduces T=double container e{5, 6}; // Error: there is no std::iterator_traits<int>::value_type
用于重载决议的虚构构造函数(如上所述)如果是从显式构造函数形成,或是从声明为 explicit 的用户定义推导指引形成,则为显式的。与往常一样,这种构造函数在复制初始化语境中会被忽略
template<class T> struct A { explicit A(const T&, ...) noexcept; // #1 A(T&&, ...); // #2 }; int i; A a1 = {i, i}; // error: cannot deduce from rvalue reference in #2, // and #1 is explicit, and not considered in copy-initialization. A a2{i, i}; // OK, #1 deduces to A<int> and also initializes A a3{0, i}; // OK, #2 deduces to A<int> and also initializes A a4 = {0, i}; // OK, #2 deduces to A<int> and also initializes template<class T> A(const T&, const T&) -> A<T&>; // #3 template<class T> explicit A(T&&, T&&) -> A<T>; // #4 A a5 = {0, 1}; // error: #3 deduces to A<int&> // and #1 & #2 result in same parameter constructors. A a6{0, 1}; // OK, #4 deduces to A<int> and #2 initializes A a7 = {0, i}; // error: #3 deduces to A<int&> A a8{0, i}; // error: #3 deduces to A<int&> // Note: check https://github.com/cplusplus/CWG/issues/647, claiming that // examples a7 and a8 are incorrect, to be possibly replaced as //A a7 = {0, i}; // error: #2 and #3 both match, overload resolution fails //A a8{i,i}; // error: #3 deduces to A<int&>, // // #1 and #2 declare same constructor
在构造函数或构造函数模板的形参列表中使用成员 typedef 或别名模板本身不会使得隐式生成的指引的对应形参成为非推导语境。
template<class T> struct B { template<class U> using TA = T; template<class U> B(U, TA<U>); // #1 }; // Implicit deduction guide generated from #1 is the equivalent of // template<class T, class U> // B(U, T) -> B<T>; // rather than // template<class T, class U> // B(U, typename B<T>::template TA<U>) -> B<T>; // which would not have been deducible B b{(int*)0, (char*)0}; // OK, deduces B<char*>
别名模板的推导当函数式转型或变量声明使用别名模板
template<class T> class unique_ptr { /* ... */ }; template<class T> class unique_ptr<T[]> { /* ... */ }; template<class T> unique_ptr(T*) -> unique_ptr<T>; // #1 template<class T> unique_ptr(T*) -> unique_ptr<T[]>; // #2 template<class T> concept NonArray = !std::is_array_v<T>; template<NonArray A> using unique_ptr_nonarray = unique_ptr<A>; template<class A> using unique_ptr_array = unique_ptr<A[]>; // generated guide for unique_ptr_nonarray: // from #1 (deduction of unique_ptr<T> from unique_ptr<A> yields T = A): // template<class A> // requires(argument_of_unique_ptr_nonarray_is_deducible_from<unique_ptr<A>>) // auto F(A*) -> unique_ptr<A>; // from #2 (deduction of unique_ptr<T[]> from unique_ptr<A> yields nothing): // template<class T> // requires(argument_of_unique_ptr_nonarray_is_deducible_from<unique_ptr<T[]>>) // auto F(T*) -> unique_ptr<T[]>; // where argument_of_unique_ptr_nonarray_is_deducible_from can be defined as // template<class> // class AA; // template<NonArray A> // class AA<unique_ptr_nonarray<A>> {}; // template<class T> // concept argument_of_unique_ptr_nonarray_is_deducible_from = // requires { sizeof(AA<T>); }; // generated guide for unique_ptr_array: // from #1 (deduction of unique_ptr<T> from unique_ptr<A[]> yields T = A[]): // template<class A> // requires(argument_of_unique_ptr_array_is_deducible_from<unique_ptr<A[]>>) // auto F(A(*)[]) -> unique_ptr<A[]>; // from #2 (deduction of unique_ptr<T[]> from unique_ptr<A[]> yields T = A): // template<class A> // requires(argument_of_unique_ptr_array_is_deducible_from<unique_ptr<A[]>>) // auto F(A*) -> unique_ptr<A[]>; // where argument_of_unique_ptr_array_is_deducible_from can be defined as // template<class> // class BB; // template<class A> // class BB<unique_ptr_array<A>> {}; // template<class T> // concept argument_of_unique_ptr_array_is_deducible_from = // requires { sizeof(BB<T>); }; // Use: unique_ptr_nonarray p(new int); // deduced to unique_ptr<int> // deduction guide generated from #1 returns unique_ptr<int> // deduction guide generated from #2 returns unique_ptr<int[]>, which is ignored because // argument_of_unique_ptr_nonarray_is_deducible_from<unique_ptr<int[]>> is unsatisfied unique_ptr_array q(new int[42]); // deduced to unique_ptr<int[]> // deduction guide generated from #1 fails (cannot deduce A in A(*)[] from new int[42]) // deduction guide generated from #2 returns unique_ptr<int[]> |
(自 C++20 起) |
[编辑] 注解
仅当不存在模板实参列表时才执行类模板实参推导。若指定了模板实参列表,则不进行推导。
std::tuple t1(1, 2, 3); // OK: deduction std::tuple<int, int, int> t2(1, 2, 3); // OK: all arguments are provided std::tuple<> t3(1, 2, 3); // Error: no matching constructor in tuple<>. // No deduction performed. std::tuple<int> t4(1, 2, 3); // Error
聚合的类模板实参推导通常需要用户定义的推导指引 template<class A, class B> struct Agg { A a; B b; }; // implicitly-generated guides are formed from default, copy, and move constructors template<class A, class B> Agg(A a, B b) -> Agg<A, B>; // ^ This deduction guide can be implicitly generated in C++20 Agg agg{1, 2.0}; // deduced to Agg<int, double> from the user-defined guide template<class... T> array(T&&... t) -> array<std::common_type_t<T...>, sizeof...(T)>; auto a = array{1, 2, 5u}; // deduced to array<unsigned, 3> from the user-defined guide |
(直至 C++20) |
用户定义的推导指引不必是模板
template<class T> struct S { S(T); }; S(char const*) -> S<std::string>; S s{"hello"}; // deduced to S<std::string>
在类模板的作用域内,没有形参列表的模板名称是注入类名,可以用作类型。在该情况下,类实参推导不会发生,且必须显式提供模板形参
template<class T> struct X { X(T) {} template<class Iter> X(Iter b, Iter e) {} template<class Iter> auto foo(Iter b, Iter e) { return X(b, e); // no deduction: X is the current X<T> } template<class Iter> auto bar(Iter b, Iter e) { return X<typename Iter::value_type>(b, e); // must specify what we want } auto baz() { return ::X(0); // not the injected-class-name; deduced to be X<int> } };
在重载决议中,偏序优先于函数模板是否从用户定义的推导指引生成:若从构造函数生成的函数模板比从用户定义的推导指引生成的函数模板更特化,则选择从构造函数生成的函数模板。由于复制推导候选项通常比包装构造函数更特化,因此此规则意味着复制通常优先于包装。
template<class T> struct A { A(T, int*); // #1 A(A<T>&, int*); // #2 enum { value }; }; template<class T, int N = T::value> A(T&&, int*) -> A<T>; //#3 A a{1, 0}; // uses #1 to deduce A<int> and initializes with #1 A b{a, 0}; // uses #2 (more specialized than #3) to deduce A<int> and initializes with #2
当早期的决胜局,包括偏序,未能区分两个候选项函数模板时,应用下列规则
- 从用户定义的推导指引生成的函数模板优先于隐式地从构造函数或构造函数模板生成的函数模板。
- 复制推导候选项优先于所有其他隐式地从构造函数或构造函数模板生成的函数模板。
- 隐式地从非模板构造函数生成的函数模板优先于隐式地从构造函数模板生成的函数模板。
template<class T> struct A { using value_type = T; A(value_type); // #1 A(const A&); // #2 A(T, T, int); // #3 template<class U> A(int, T, U); // #4 }; // #5, the copy deduction candidate A(A); A x(1, 2, 3); // uses #3, generated from a non-template constructor template<class T> A(T) -> A<T>; // #6, less specialized than #5 A a(42); // uses #6 to deduce A<int> and #1 to initialize A b = a; // uses #5 to deduce A<int> and #2 to initialize template<class T> A(A<T>) -> A<A<T>>; // #7, as specialized as #5 A b2 = a; // uses #7 to deduce A<A<int>> and #1 to initialize
到 cv 无限定模板形参的右值引用若该形参是类模板形参,则不是转发引用
template<class T> struct A { template<class U> A(T&&, U&&, int*); // #1: T&& is not a forwarding reference // U&& is a forwarding reference A(T&&, int*); // #2: T&& is not a forwarding reference }; template<class T> A(T&&, int*) -> A<T>; // #3: T&& is a forwarding reference int i, *ip; A a{i, 0, ip}; // error, cannot deduce from #1 A a0{0, 0, ip}; // uses #1 to deduce A<int> and #1 to initialize A a2{i, ip}; // uses #3 to deduce A<int&> and #2 to initialize
当从类型为所讨论的类模板的特化的单个实参初始化时,默认情况下,复制推导通常优先于包装
std::tuple t1{1}; //std::tuple<int> std::tuple t2{t1}; //std::tuple<int>, not std::tuple<std::tuple<int>> std::vector v1{1, 2}; // std::vector<int> std::vector v2{v1}; // std::vector<int>, not std::vector<std::vector<int>> (P0702R1) std::vector v3{v1, v2}; // std::vector<std::vector<int>>
在复制与包装的特殊情况之外,列表初始化中对初始化器列表构造函数的强烈偏好仍然完整。
std::vector v1{1, 2}; // std::vector<int> std::vector v2(v1.begin(), v1.end()); // std::vector<int> std::vector v3{v1.begin(), v1.end()}; // std::vector<std::vector<int>::iterator>
在引入类模板实参推导之前,避免显式指定实参的常用方法是使用函数模板
std::tuple p1{1, 1.0}; //std::tuple<int, double>, using deduction auto p2 = std::make_tuple(1, 1.0); //std::tuple<int, double>, pre-C++17
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_deduction_guides |
201703L |
(C++17) | 类模板的模板实参推导 |
201907L |
(C++20) | 聚合与别名的 CTAD |
[编辑] 缺陷报告
下列行为更改缺陷报告被追溯应用到先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
CWG 2376 | C++17 | 即使声明的变量类型 与要推导其形参的类模板不同,也会执行 CTAD |
在此情况下不执行 CTAD |
CWG 2628 | C++20 | 隐式推导指引不传播约束 | 传播约束 |
CWG 2697 | C++20 | 缩略函数模板是否 允许用于用户定义的推导指引是不明确的 |
已禁止 |
CWG 2707 | C++20 | 推导指引不能拥有尾随 requires 子句 | 它们可以 |
CWG 2714 | C++17 | 隐式推导指引不考虑 构造函数的默认实参 |
考虑它们 |
CWG 2913 | C++20 | CWG issue 2707 的决议令推导指引 语法与函数声明语法不一致 |
已调整语法 |
P0702R1 | C++17 | 初始化器列表构造函数能抢占 复制推导候选项,导致包装 |
初始化器列表阶段 复制时跳过 |