SHR
SHR

Reputation: 496

passing a stringstream to a function

I'm trying to pass a stringstream, from a file, to a function. When I'm calling the template function, I'm getting an error: no matching function for call to 'toFile'. I verified that the life is opened and the data has passed from it to the stringstream.

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

using namespace std;

template <typename T1>
void toFile(string type, int NumOfElements, stringstream& ss){

   T1* myArray = new T1[NumOfElements];  // declaring new array to store the elements
   int value;

   for(int i = 0; i < NumOfElements; i++){ // store the elements in the array
       ss >> value;
       myArray[i] = value;
       cout << myArray[i] << " ";
   }
}


int main(int argc, char *argv[])
{
   ifstream ins;
   ofstream outs;
   string strg1;
   string type;
   int NumOfElements = 0;
   stringstream inputString;

   ins.open(argv[1]);

   if(argc<1) {
        cout << "please provide the file path." << endl;
            exit(1);
    }


   while (getline(ins, strg1)){ // reading  line from the file
   inputString.clear(); // clearing the inputString before reading a new line
   inputString << strg1;

   inputString >> type ;        // reading 1st element in a row
   inputString >> NumOfElements; // reading 2nd element in a row

   toFile(type, NumOfElements, inputString);
  }
   ins.close();
       return 0;
}

Upvotes: 1

Views: 330

Answers (2)

aschepler
aschepler

Reputation: 72271

toFile is a function template, so it can only be called with a template parameter. Sometimes function templates can deduce their parameters from their arguments, but since T1 isn't used in your argument list, there's no way to deduce it. You'll need to explicitly provide the template argument instead, for example:

toFile<int>(type, NumOfElements, inputString);

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

You didn't specify a template argument for toFile, so the template cannot be instantiated.

Thus, no function toFile<T> (which would have been an instantiation of said template) exists.

The argument cannot be deduced automatically because none of the function arguments have anything to do with it.

Upvotes: 2

Related Questions