类模板参数推导 (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
的特化派生的类,则省略列表初始化的第一阶段(考虑初始化器列表构造函数)。
这些虚构的构造函数是假想类类型的公有成员。如果指引是由显式构造函数形成,或指引被声明为explicit,则它们是显式的。如果重载决议失败,程序将格式错误。否则,所选的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(可选) template-name ( parameter-list ) -> simple-template-id requires-clause(可选) ; |
(1) | ||||||||
template < template-parameter-list> requires-clause(可选)explicit(可选) template-name ( parameter-list ) -> simple-template-id requires-clause(可选) ; |
(2) | ||||||||
template-parameter-list | - | 一个非空的逗号分隔的模板参数列表 |
explicit | - | 一个explicit 说明符 |
template-name | - | 其参数将被推导的类模板的名称 |
parameter-list | - | 一个(可能为空的)参数列表 |
simple-template-id | - | 一个简单模板标识符 |
requires-clause | - | (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
功能测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_deduction_guides |
201703L |
(C++17) | 类模板的模板参数推导 |
201907L |
(C++20) | 聚合和别名的CTAD |
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
CWG 2376 | C++17 | 即使声明的变量类型不同于其参数将被推导的类模板,也会执行CTAD 当声明的变量类型与要推导参数的类模板不同时 |
不执行 CTAD |
CWG 2628 | C++20 | 隐式推导指引未传播约束 | 传播约束 |
CWG 2697 | C++20 | 不清楚是否允许在用户定义的推导指引中使用缩写函数模板语法 用户定义的推导指引不允许使用缩写函数模板语法 |
已禁止 |
CWG 2707 | C++20 | 推导指引不能有尾随的requires子句 | 推导指引可以有尾随的requires子句 |
CWG 2714 | C++17 | 隐式推导指引未考虑构造函数的默认参数 考虑构造函数的默认参数 |
考虑它们 |
CWG 2913 | C++20 | CWG 问题 2707 的解决方案使得推导指引语法与函数声明语法不一致 调整了语法 |
调整了语法 |
P0702R1 | C++17 | 初始化器列表构造函数可以抢占复制推导候选,导致包装 初始化器列表阶段 |
复制时跳过 复制时跳过 |