【发布时间】:2021-05-19 04:55:57
【问题描述】:
我需要您的帮助来找出以下代码无法编译的原因。
#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(){
不是应该选择更专业的功能吗?即只有一个模板(第一个)。
【问题讨论】:
-
“更专业”是通过参数完成的,而不是模板参数;至于空包抢七。
-
对于 C++17 解决方案,请参阅stackoverflow.com/a/43070233
标签: c++ c++11 recursion variadic-templates