Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 模板推导和为参数包显式提供的类型_C++_Templates_Variadic Functions_Pack_Template Argument Deduction - Fatal编程技术网

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
    匹配,推断为
    1,2,3
    ->OK
  • 然后从函数参数推导出
    T
    ,即
    4
    int
    ->OK
当你写foo(4);:

  • 1、2、3、int
    int…N
    ->错误匹配

是什么导致了包的贪婪?当有一个非类型包紧跟着一个类型,甚至是一个类型包时,编译器为什么不能检测边界来停止对非类型参数的解析?每个人都应该看到“int”完全不同于一个CONExPR整数值。@ GSI,因为这是C++的语法。而且这很可能是因为处理这个特定情况的复杂性增加的代价是不合理的。
template <int... N, class T>
auto foo(T) {};

auto test()
{
    foo<1, 2, 3>(4); // OK
    foo<1, 2, 3, int>(4); // ERROR
}