为什么在使用typedef时类推导指南会失败

Why does the class deduction guide fail when using a typedef?

本文关键字:失败 typedef 为什么      更新时间:2023-10-16

在我目前编写的一段代码中,我使用了类推导指南。您可以在下面找到一个简单(但毫无意义的示例(的代码摘录:我有一个类User,它从构造函数的第一个参数派生出第一个模板参数,从作为第二个参数提供的参数包的大小派生出第二个模板参数:

#include <cstddef>
#include <type_traits>
/// First constructor parameter, which can be used in order to derive the boolean
template <int, bool switcher> struct P1 {};
/// Class which depends on the boolean flag (from first parameter) and the amount of elements provided.
template <bool switcher, size_t amountKids> struct User {
template <int p1, int... pn> explicit constexpr User(P1<p1, switcher> &child,
P1<pn, switcher>... parents) noexcept {}
};
/// Deduction guide
template <bool f, int p1, int... pn> User(P1<p1, f> &child, P1<pn, f> ...) ->User<f, sizeof...(pn) + 1>;
int main() {
P1<1, true> child;
User sa{child, P1<1, true>{}};
User sa2{child, child, child};
}

这很好用(编译(。然而,当我通过将参数包的类型替换为依赖于模板参数switcher的类型来进行微小修改时,推导失败:

#include <cstddef>
#include <type_traits>
/// First constructor parameter, which can be used in order to derive the boolean
template <int, bool switcher> struct P1 {};
/// In the real example, conditional_type holds a different type, depending on the #bool
template <bool, typename T> struct conditional_type { using type = T; };
template <bool switcher, typename T> using conditional_type_t = typename conditional_type<switcher, T>::type;
template <bool switcher, size_t amountKids> struct User {
template <int p1, int... pn> explicit constexpr User(P1<p1, switcher> &child,
conditional_type_t<switcher, P1<pn, switcher>>... parents) noexcept {}
};
template <bool f, int p1, int... pn> User(P1<p1, f> &child, conditional_type_t<f, P1<pn, f>>...) ->User<f, sizeof...(pn) + 1>;
int main() {
conditional_type_t<true, P1<1, true>> child2;
P1<1, true> child;
static_assert(std::is_same_v<decltype(child), decltype(child2)>);
User sa{child, P1<1, true>{}}; //< fails: 2 arguments provided, expecting one, can't derive amountKids
User sa2{child, child, child}; //< fails: 
}

为什么?

这两种代码变体都可以在这里找到。

第二个例子中的推导指南相当于我们用别名替代的结果

template <bool f, int p1, int... pn>
User(P1<p1, f> &child, typename conditional_type<f, P1<pn, f>>::type ...)
-> User<f, sizeof...(pn) + 1>;

A是依赖类型的任何语法typename A::B中,类型A是非推导上下文。由于pn只出现在非推导的上下文中,因此它永远无法推导,因此推导指南永远无法使用。

出于类似的原因,User的构造函数永远不能与多个参数一起使用,即使明确指定了User的模板参数也是如此。