Question

I have the following template function which prints to cout:

 template <typename T> void  prn_vec(const std::vector < T >&arg, string sep="") 
    {
        for (unsigned n = 0; n < arg.size(); n++) { 
            cout << arg[n] << sep;    
        }
        return;
    } 

    // Usage:
    //prn_vec<int>(myVec,"\t");

    // I tried this but it fails:
    /*
      template <typename T> void  prn_vec_os(const std::vector < T >&arg, 
      string    sep="",ofstream fn)
      {
        for (unsigned n = 0; n < arg.size(); n++) { 
            fn << arg[n] << sep;      
        }
        return;
      }
   */

How can I modify it so that it also takes file handle as input and print out to that file as referred by the filehandle?

So that we can do something like:

#include <fstream>
#include <vector>
#include <iostream>
int main () {

  vector <int> MyVec;
  MyVec.push_back(123);
  MyVec.push_back(10);

  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";


  // prn_vec(MyVec,myfile,"\t");

  myfile.close();
  return 0;
}
Was it helpful?

Solution

template <typename T> 
ostream& prn_vec(ostream& o, const std::vector < T >&arg, string sep="") 
{
    for (unsigned n = 0; n < arg.size(); n++) { 
        o << arg[n] << sep;    
    }
    return o;
} 

int main () {

  vector <int> MyVec;
  // ...
  ofstream myfile;

  // ...
  prn_vec(myfile, MyVec, "\t");

  myfile.close();
  return 0;
}

OTHER TIPS

Pass the ofstream by reference:

template <typename T> void  prn_vec_os(
    const std::vector < T >&arg,
    string sep,
    ofstream& fn)

Also, remove the default value for sep, or re-order the arguments, since you cannot have a default argument in the middle of the argument list with non-defaults following.

EDIT: As suggested in the comments and implemented in dirkgently's answer, you most likely want to use an ostream instead of an ofstream, so as to be more general.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top