c++stringoperator-overloadinggetlineextraction-operator

Locally Overriding the string Extraction Operator


I have a set of utility functions which read in lines from a stream rather than reading word by word. They work with strings, so I'd like to locally change the string extraction operator within the scope of these functions only. Is that possible?


What I'm doing right now is to create a struct that is a string and writing an extraction operator for that struct only.

struct line{
    string str;
};

istream& operator>>(istream& lhs, line& rhs){
    return getline(lhs, rhs.str);
}

And then extracting an istream like this:

vector<line> foo{ istream_iterator<line>(istringstream("Lorem Ipsum\nLorem Ipsum")), istream_iterator<line>() };

This works fine but I do not like the struct line wrapper. What I'm asking is, can I locally overload istream& operator>>(istream& lhs, string& rhs) to accomplish this instead?


Solution

  • What you're asking for is not possible. There already exists an istream& >>(istream&, string& ), so you can't simply overwrite it. Providing another type is already the way to do it.

    One thing you could do is provide a conversion from line to std::string so that your container can just be std::vector<std::string> instead of std::vector<line>

    struct line{
        string str;
        operator string() const { return str; }
    };
    
    istringstream iss("Lorem Ipsum\nLorem Ipsum");
    vector<string> foo{istream_iterator<line>(iss),
                       istream_iterator<line>() };
    

    That way the line type doesn't have to exist outside of the extraction process and bleed into the rest of your codebase.