模板推导和参数包的显式提供类型
template deduction and explicitly supplied types for parameter packs
我将简化和缩短这个问题以方便回答。
本质是:
为什么编译和执行此代码
# include <iostream>
template <class A> class Goofy {};
template <int N, template <class> class B, class A, int ... K, class ... Z>
void f ( A a, B<A> b, Z ... z )
{
std::cout << "I'm executed" << std::endl;
}
int main()
{
Goofy<int> goofy;
f<1, Goofy, int, 2, 3, 4>(2,goofy,1.3,'a',1.f);
}
而以下不是?
# include <iostream>
template <class A> class Goofy {};
template <int N, template <class> class B, class A, int ... K, class ... Z>
void f ( A a, B<A> b, Z ... z )
{
std::cout << "I'm executed" << std::endl;
}
int main()
{
Goofy<int> goofy;
f<1, Goofy, int, 2, 3, 4, double, char, float>(2,goofy,1.3,'a',1.f);
}
唯一的区别是显式和一致的类型供应实例化包Z
.
我不认为这会以编译错误告终,而且诊断告诉模板扣除/替换失败时,恕我直言,不需要扣除。
谁能向我解释一下?
我使用了编译器 GNU 7.3.1 和 clang 4.0.1,两者的行为相同,所以我担心我的推理中存在严重错误......但我找不到什么。
您的代码可以简化为:
template <int... N, class T>
auto foo(T) {};
auto test()
{
foo<1, 2, 3>(4); // OK
foo<1, 2, 3, int>(4); // ERROR
}
原因是可变参数是贪婪的。这就是为什么在明确陈述它们时它们需要排在最后的原因。
当你写foo<1, 2, 3>(4);
:
-
1, 2, 3
与int... N
匹配 ->N
推导出1, 2, 3
->确定 - 然后从函数参数推导出
T
,即4
int
-> 确定
当你写foo<1, 2, 3, int>(4);
:
-
1, 2, 3, int
与int... N
-> 错误匹配
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法