C++ 模板推导和为参数包显式提供的类型
我将简化和缩短这一问题,以便于回答 关键是: 为什么要编译和执行此代码C++ 模板推导和为参数包显式提供的类型,c++,templates,variadic-functions,pack,template-argument-deduction,C++,Templates,Variadic Functions,Pack,Template Argument Deduction,我将简化和缩短这一问题,以便于回答 关键是: 为什么要编译和执行此代码 # 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:
# 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);
}
#包括
模板类Goofy{};
模板
无效f(A,B,Z…Z)
{
std::cout您的代码可以缩减为:
template <int... N, class T>
auto foo(T) {};
auto test()
{
foo<1, 2, 3>(4); // OK
foo<1, 2, 3, int>(4); // ERROR
}
模板
自动foo(T){};
自动测试()
{
foo(4);//好的
foo(4);//错误
}
原因是变量参数是贪婪的。这就是为什么在显式声明它们时它们必须是最后一个
当你写foo(4);
:
与1,2,3
->int…N
匹配,推断为N
->OK1,2,3
- 然后从函数参数推导出
,即T
到4
->OKint
与1、2、3、int
->错误匹配int…N
template <int... N, class T>
auto foo(T) {};
auto test()
{
foo<1, 2, 3>(4); // OK
foo<1, 2, 3, int>(4); // ERROR
}