c++ - Initializing reference to istream -
i trying write program can process either stdin or file specified on command line.
i'm doing trying initialize reference istream
either refer cin
or ifstream
, using conditional.
(similar techniques described here , here)
but when try ifstream
, seem error basic_istream move-constructor declared protected
.
istream& reftocin ( cin ); // ok const istream& reftofile = ifstream(args[1]); // ok const istream& instream ( fileisprovided()? ifstream(args[1]) : cin ); // causes error: // std::basic_istream<char,std::char_traits<char>>::basic_istream' : // cannot access protected member declared in class std::basic_istream<char,std::char_traits<char>> processstream(instream); // either file or cin
can reasonably done way? there alternative i'm overlooking?
the problem code following:
your left-hand side of ternary operator temporary (rvalue). however, right hand-side lvalue (cin
lvalue). result, compiler trying create temporary out of cin
, , fails because of copy constructor being not available.
as sultions - can replace rdbuf()
of cin rdbuf()
of file, , use cin
everywhere.
here's ultimate solution op came with:
ifstream file; std::streambuf* old_cin_buf = cin.rdbuf(); // store old value if (fileisprovided()) { file.open(args[1]); old_cin_buf = cin.rdbuf(file.rdbuf()); // replace readbuffer on cin. // store previous value well. } // use cin operations now. either use file or stdin appropriate. ... // restore original value, in case changed using file. cin.rdbuf(old_cin_buf); // better done before file object here goes out of scope