c++ - 使用可变参数模板打印列表

标签 c++ c++11 recursion variadic-templates

我需要你的帮助来找出为什么以下代码无法编译。

#include <iostream>

template <int I>
void foo(){
  std::cout << I << std::endl;
  std::cout << "end of list" << std::endl;
}

template <int I, int ... Ints>
void foo(){
  std::cout << I << std::endl;
  foo<Ints...>();
}


int main(){
  foo<1, 2>();
  return 0;
}

我遇到了这个错误。

function_parameter_pack.cpp: In instantiation of ‘void foo() [with int I = 1; int ...Ints = {2}]’:
function_parameter_pack.cpp:17:13:   required from here
function_parameter_pack.cpp:12:15: error: call of overloaded ‘foo<2>()’ is ambiguous
   foo<Ints...>();
   ~~~~~~~~~~~~^~
function_parameter_pack.cpp:4:6: note: candidate: void foo() [with int I = 2]
 void foo(){
      ^~~
function_parameter_pack.cpp:10:6: note: candidate: void foo() [with int I = 2; int ...Ints = {}]
 void foo(){

不是应该选择更专业的功能吗?即只有一个模板(第一个)。

最佳答案

foo<2>同样匹配两个模板(因为 int... 也匹配零个 int s)这就是编译器提示歧义的原因。

Isn't a more specialized function is supposed to be chosen?

是的,但这些都同样特别。通过查看函数的参数而不是模板参数来推断哪个是更专业的匹配函数。

解决这个问题的一种方法是使第二个函数模板采用 2 个或更多模板参数:

#include <iostream>

template<int I>
void foo() {
    std::cout << I << std::endl;
    std::cout << "end of list" << std::endl;
}

template<int I, int J, int... Ints>
void foo() {
    std::cout << I << std::endl;
    foo<J, Ints...>();
}

int main() {
    foo<1>();
    foo<1, 2>();
    foo<1, 2, 3>();
}

关于c++ - 使用可变参数模板打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66222696/

相关文章:

c++ - 指向具有 vector 内存泄漏的对象的指针

c++11 聚合初始化之前的值初始化

mysql - 带循环计数器的递归查询

c++ - 分配的值占用的空间超过类型的可用空间会怎样?

C++:为什么我的二分搜索函数会陷入无限循环?

c++ - 在 map 中搜索 : Member vs. 非成员 lower_bound

c++ - 用Pin工具打印每条指令的程序和函数名

c++ - 为什么 std::bind 接受比绑定(bind)函数更多的参数?

php - 如何替换多维数组中的字符串?

javascript - 如何将整数数组递增 1