Re-assigning an istream&...

Consider:

1
2
3
4
5
6
7
class X{
    //...
    istream& source;
public:
    //...
    void set_source(const istream& ist){/*???*/}
}


How can something of this manner be implemented? Perhaps while also supporting:

1
2
3
4
//...
X var(cin);
var = X(ifstream("myfile.txt"));
//... 


Thanks in advance!

Note: I know having an istream& as a class member is weird but bear with me on this.
Last edited on
X holds an lvalue reference to std::istream.
This won't work: var = X(ifstream("myfile.txt")); as ifstream("myfile.txt") is an rvalue.

To simulate an assignable or copyable reference, wrap it in std::reference_wrapper<>
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

1
2
3
4
5
6
7
8
9
10
11
12
13
struct X
{
    X( std::istream& stm ) : source(stm) {}
    X( const X& ) = default ;
    X& operator= ( const X& ) = default ;
    ~X() = default ;

    X& operator= ( std::istream& stm ) { source = stm ; return *this ; }

    // ...

    std::reference_wrapper<std::istream> source ;
};

http://coliru.stacked-crooked.com/a/f91fe1b926d7b53b
Ty sir this is the kind of thing I was looking for. I understand that istreams copy constructor has been deleted btw ;).
Topic archived. No new replies allowed.