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";
If you want to accept only one object with "<<" operator, you can directly override it:
If you want to accept multiple object with a single operator << , you can check how Eigen library implement like this, for example: