user2328447
user2328447

Reputation: 1847

Compile errors when implementing stream operators

I am trying to implement stream extraction operators for a stream class which inherits std::basic_iostream<char>. Unfortunately I get compile errors I don't really understand.

This is my simplified (non-functional) code:

#include <iostream>

class MyWhateverClass {
public:
    int bla;
    char blup;
};

class MyBuffer : public std::basic_streambuf<char> {
};

class MyStream : public std::basic_iostream<char> {
    MyBuffer myBuffer;
public:
    MyStream() : std::basic_iostream<char>(&myBuffer) {}

    std::basic_iostream<char>& operator >> (MyWhateverClass& val) {
        *this >> val.bla; 
        *this >> val.blup; 
        return *this; 
    }
};

int main()
{
    MyStream s;
    s << 1;
    int i;
    s >> i;

    return 0;
}

I'm getting two similar errors: C2678 binary '>>': no operator found which takes a left-hand operand of type 'MyStream', one in the line where I implement the operator and one in the line where I get an int from the stream.

Funny detail is, that both errors are gone when I remove the operator implementation.

Can anyone tell what's happening here?

Upvotes: 0

Views: 52

Answers (1)

Innokentiy Alaytsev
Innokentiy Alaytsev

Reputation: 840

I have resolved the issue. The reason you get compilation error is shadowing. Your MyStream::operator>>(MyWhateverClass&) shadows all versions of std::basic_iostream::operator>>. In order to resolve this issue you need to use using declaration:

class MyStream : public std::basic_iostream<char> {
    MyBuffer myBuffer;
public:
    MyStream() : std::basic_iostream<char>(&myBuffer) {}

    using std::basic_iostream<char>::operator>>;
    std::basic_iostream<char>& operator >> (MyWhateverClass& val) {
        *this >> val.bla;
        *this >> val.blup;
        return *this;
    }
};

P.S. The initial answer was totally wrong, no need to save it)

Upvotes: 1

Related Questions