mardi 16 février 2021

print a list of numbers using template metaprogramming

I am unable to figure out why does following code not compile. Could you guys please help me?

#include <iostream>

template <typename T, typename ...Args>
void foo(T i, Args ... args){
  std::cout << i << std::endl;
  foo(args...);
}

template <typename T>
void foo(T i){
  std::cout << i << std::endl;
  std::cout << "end of list" << std::endl;
}

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

I get the following error

function_parameter_pack.cpp: In instantiation of ‘void foo(T, Args ...) [with T = int; Args = {}]’:
function_parameter_pack.cpp:18:6:   required from ‘void foo(T, Args ...) [with T = int; Args = {int}]’
function_parameter_pack.cpp:47:11:   required from here
function_parameter_pack.cpp:18:6: error: no matching function for call to ‘foo()’
   foo(args...);
   ~~~^~~~~~~~~
function_parameter_pack.cpp:16:6: note: candidate: template<class T, class ... Args> void foo(T, Args ...)
 void foo(T i, Args ... args){
      ^~~
function_parameter_pack.cpp:16:6: note:   template argument deduction/substitution failed:
function_parameter_pack.cpp:18:6: note:   candidate expects at least 1 argument, 0 provided
   foo(args...);

It seems error is happening during base case. But I am not able to understand why.

I tried following base-case also but got the same error

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

Aucun commentaire:

Enregistrer un commentaire