我有以下打印到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;
      }
   */如何修改它,使其也接受文件句柄作为输入,并按照文件句柄所引用方式打印到该文件?
这样我们就可以做一些类似的事情:
#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;
}发布于 2009-03-26 05:35:32
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;
}https://stackoverflow.com/questions/684623
复制相似问题