Search code examples
c++streamoperator-overloadingstream-operators

How to implement the extraction operator in a class?


I have a class that reads parts of a binary file into variables of different types.

class Foo {
public:
    size_t getSizeT();
    float getFloat();
    std::string getString();
private:
    std::ifstream stream;
};

Now I'd like to implement the stream extraction operator as described in this answer.

class Foo {
public:
    Foo &operator>>(Foo &foo, size_t &value);
    Foo &operator>>(Foo &foo, float &value);
    Foo &operator>>(Foo &foo, std::string &value);
private:
    std::ifstream stream;
};

The code fails to compile with this error message: error C2804: binary 'operator >>' has too many parameters. How to properly override the stream extraction operator? It should distinguish between types and be chainable.


Solution

  • As free function, operator signature should be:

    Foo& operator >>(Foo& foo, size_t& value);
    

    As member function (your case), it should be:

    Foo& operator >>(size_t& value);