How to operator overload fstream in a new class?

68 views Asked by At

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";
1

There are 1 answers

0
Austin Yang On

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"