Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was programming a simple program in c++ but i get an error saying No matching function for call to 'passarray'

here is my code:

C++
#include <iostream>
#include <string.h>
#include <vector>

using namespace std;

template <typename t, typename t2>

void passarray(vector<t> myvec, T2 value) {
    myvec.push_back(value);
}

template <typename... t, typename t2>
void givevalue(vector<t2> myvec,T... myval) {
    passarray(myvec, myval...);
}

int main(){
    vector<int> myvec;
    givevalue(myvec, 233, 45);
}

Can someone please tell me why the code is not running and how to fix it. Thank you

What I have tried:

I have tried looking up the problem and trying to learn more on variadic template.
Posted
Updated 2-Sep-21 2:46am
v6
Comments
Richard MacCutchan 2-Sep-21 8:07am    
I am not an expert in templates, but it would appear that you are trying to pass a parameter pack(multiple items) to a function that only accepts a single value.

You also need to check your typenames are all the correct spelling and case(i.e. T2 is not the same as t2).

1 solution

Try
C++
#include <iostream>
#include <vector>

using namespace std;

template <typename T>
  void passarray(vector<T> &  myvec, T value)
  {
    myvec.push_back(value);
  }

template <typename T>
  void givevalue(vector <T> & v){}

template <typename T, typename... Ts>
  void givevalue(vector<T> & v, T x, Ts... xs)
  {
    passarray(v, x);
    givevalue(v, xs...);
  }


int main()
{

  vector<int> myvec {12,7};

  givevalue(myvec, 5, 6, 7);
  givevalue(myvec, 42);

  for (auto x : myvec)
    cout << x << " ";

  cout << endl;
}
 
Share this answer
 
v2
Comments
iwanttoaskquestions 3-Sep-21 1:39am    
Thank you it works. But I am having a problem understanding why. Can you please explain it to me?
CPallini 3-Sep-21 2:41am    
Try to remove
template <typename T>
  void givevalue(vector <T> & v){}

and see the error messages, to have some insight.
Moreover, I suggest you to read some tutorials on variadic templates, the could explain better than me what is happening.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900