views:

560

answers:

2

Dear all,

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;
}
+2  A: 
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;
}
dirkgently
neversaint
ofstream is a specialization of ostream: All ofstreams are ostreams but the reverse is not true. This is helpful when you want to print to a string stream or a custom serializer.
dirkgently
+1  A: 

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.

camh
Your code has `ofstream` and not `ostream`. Typo?
dirkgently
No, just cut'n'paste from the original, adding an ampersand.
camh
neversaint
camh