C ++ stream reference as a class member

I have a class that looks something like this:

#include <iostream>

class A {
public:
    A (std::istream& is): _is(is) {}

    void setInputSource (std::istream& is) {
        _is = is;
    }

    A& operator>> (int& x) {
        _is >> x;
        return *this;
    }

private:
    std::istream& _is;
};

And I want the member to _isact as a link. I mean, it should "point" to the external one std::istream, and I do not want the method to setInputSource()copy the stream that is passed as an argument. The problem is that the program will not compile, because this method, which I mentioned, is trying to access the operator=class std::basic_istream<char>.

My goal is to make the class behave as expected in such a program:

int main() {
    int a, b;

    std::ifstream ifs("myfile.txt");
    A myA(std::cin);

    myA >> a;
    myA.setInputSource(ifs);
    myA >> b;

    return 0;
}

I thought of using pointers instead, but I prefer to use references, because I like the fact that they guarantee that they will not have invalid values, and it seems to me that this is a more elegant approach.

+4
3

, . . , .

, , ,

. , , , , .

+4

. - .

, , , .

, myA .

int main() {
    int a, b;

    A myA(std::cin);
    myA >> a;

    {
       std::ifstream ifs("myfile.txt");
       myA.setInputSource(ifs);
    }

    myA >> b;

    return 0;
}

, .

+1

It looks like you just want to change the buffer:

class A
{
public:
    A (std::istream& is)
        : m_is(is.rdbuf())
    { }

    void setInputSource(std::istream& is) {
        m_is.rdbuf(is.rdbuf());
    }

    // ...

private:
    std::istream m_is;
};
+1
source

Source: https://habr.com/ru/post/1526979/


All Articles