【问题标题】:Howto Pass Filehandle to a Function for Output Streaming如何将文件句柄传递给函数以进行输出流式处理
【发布时间】:2009-03-26 05:27:08
【问题描述】:

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

【问题讨论】:

    标签: c++ templates filehandle


    【解决方案1】:
    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:非常感谢。但是为什么你使用 "ostream&o" 而不是 "ofstream&o" 呢?此外,我主要使用“ofstream myfile”。
    • ofstream 是 ostream 的一种特殊形式:所有的 ofstream 都是 ostream,但反之则不然。当您想要打印到字符串流或自定义序列化程序时,这很有帮助。
    【解决方案2】:

    通过引用传递ofstream:

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

    此外,请删除 sep 的默认值,或重新排序参数,因为您不能在参数列表的中间有一个默认参数,后面跟着非默认值。

    编辑:正如 cmets 中所建议并在 dirkgently 的回答中实现的那样,您很可能希望使用 ostream 而不是 ofstream,以便更通用。

    【讨论】:

    • 不,只是从原文中剪切'n'paste,添加一个&符号。
    • @camh: 好的,我会改成“ostream&”,但是在main函数中保留“ofstream myfile”可以吗?
    • 是的。 ofstream 派生自 ostream,因此您可以在需要 ostream& 时通过引用传递它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多