为什么在使用typedef时类推导指南会失败
Why does the class deduction guide fail when using a typedef?
在我目前编写的一段代码中,我使用了类推导指南。您可以在下面找到一个简单(但毫无意义的示例(的代码摘录:我有一个类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
的模板参数也是如此。
相关文章:
- C++:TypeDef使用元组
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- 为什么在使用typedef时类推导指南会失败
- C typedef int arr [x] [y]在stackdump错误中失败
- 类模板中的 typedef 的 SFINAE 失败是指另一个类模板中的 typedef
- typedef声明定义未命名类时链接失败
- STL 复制在"typedef"类型的数组上失败