我有以下打印到 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;
}