Class 部分特化的模板参数推导

Class template argument deduction with partial specialization

我在理解允许对构造函数进行模板推导的新 C++17 功能的所有限制时遇到了一些困难。

特别是,这个例子编译正确:

struct B {};

template <typename T, typename = T>
struct A {
    A(T) {}
};

int main() {
    B b;
    A a(b); // ok
}

虽然这个没有:

struct B {};

template <typename T, typename = T>
struct A;

template <typename T>
struct A<T> {
    A(T) {}
};

int main() {
    B b;
    A a(b); // error
}

第二种情况的错误是:

main.cpp: In function ‘int main()’:
main.cpp:17:14: error: class template argument deduction failed:
         A a(b);
              ^
main.cpp:17:14: error: no matching function for call to ‘A(B&)’
main.cpp:4:12: note: candidate: template<class T, class> A(A<T, <template-parameter-1-2> >)-> A<T, <template-parameter-1-2> >
     struct A;
            ^
main.cpp:4:12: note:   template argument deduction/substitution failed:
main.cpp:17:14: note:   ‘B’ is not derived from ‘A<T, <template-parameter-1-2> >’
         A a(b);
              ^

为什么会这样?

Class 模板参数推导只考虑来自 primary class 模板的构造函数来进行推导。在第一个例子中,我们有一个构造函数,我们合成了一个函数模板:

template <class T> A<T> __f(T );

__f(b)的结果是A<B>,我们完成了。

但在第二个示例中,主要 class 模板只是:

template <typename T, typename = T>
struct A;

它没有构造函数,所以我们没有可以从中合成的函数模板。我们只有一个 hypothetical default constructor and the copy deduction guide,它们一起给了我们这个重载集:

template <class T> A<T> __f();
template <class T> A<T> __f(A<T> );

对于__f(b)两者都不可行(你得到的编译错误是关于试图匹配复制推导指南),因此推导失败。


如果你想成功,你必须写一个推导指南:

template <class T>
A(T ) -> A<T>;

这将允许 A a(b) 工作。