Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print a list using variadic templates

I need your help to find out why does following code not compile.

#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;
}

I am getting this error.

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(){

Isn't a more specialized function is supposed to be chosen? i.e one with only one template(the first one).

like image 511
atuly Avatar asked Nov 25 '25 15:11

atuly


1 Answers

foo<2> matches both templates equally well (since int... matches zero ints too) which is why the compiler complains about ambiguity.

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

Yes, but a these are equally special. Deducing which is the more specialized matching function is done by looking at the arguments to the function, not the template parameters.

One way to solve that is to make the second function template take 2 or more template parameters:

#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>();
}
like image 69
Ted Lyngmo Avatar answered Nov 27 '25 07:11

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!