how to improve my class to create output files

Viewed 32

As I need this quite often, I would like to write a class handling main ofstream activities.

Something that I could use like this:

OutputFile out("output.txt");
for (int i = 0; i < 10; ++i)
   out << i << "\n";

To this end, I wrote the following class:

class OutputFile {
  std::string filename;
  std::ofstream out;

 public:
  explicit OutputFile(std::string filename) {
    this->filename = filename;
    out.open("output/" + filename);
  }
  ~OutputFile() {
    out.close();
  }
  std::ofstream& operator()() { return out; }
};

which is almost what I wanted, however I'm overloading the operator (), such that in the example above I have to use

out() << i << "\n";

How should I modify my class such that I can use as

out << i << "\n";
1 Answers

You can overload operator<< in your class.

class OutputFile {
  std::string filename;
  std::ofstream out;

 public:
  explicit OutputFile(const std::string &filename)
    : filename(filename), out("output/" + filename) {}

  template<typename T>
  OutputFile& operator<<(const T &value) {
    out << value;
    return *this;
  }
};
Related