0

I want to wrap a new class to generate a file and make some auto resource recycle and some additional operate with the new file. So I make a new class like

class TmpFile { private: std::string tmp_file_name; std::ofstream tmp_file; public: TmpFile(const std::string &name) :tmp_file_name(name), tmp_file(tmp_file_name, ios::out | ios::trunc) {} ~TmpFile() { tmp_file.close(); //some operate afterwards using tmp_file ... } }; 

But is there a way to operator overload "<<" to write into file inside "class TmpFile" like

TmpFile f; f << "asd"; 
3

1 Answer 1

0

If you want to accept only one object with "<<" operator, you can directly override it:

class TmpFile { private: std::string tmp_file_name; std::ofstream tmp_file; public: TmpFile(const std::string &name) :tmp_file_name(name), tmp_file(tmp_file_name, ios::out | ios::trunc) {} ~TmpFile() { tmp_file.close(); //some operate afterwards using tmp_file ... } // here define your operator void operator << (const std::string& str) { // do something } }; 

If you want to accept multiple object with a single operator << , you can check how Eigen library implement like this, for example:

f << "asdf", "efsjkfl" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.