我正在尝试编写我的程序,以便它可以处理 StdIn 或命令行上指定的文件。
我通过尝试初始化对 istream
的引用来引用 cin
或 ifstream
,使用条件.
但是当我尝试使用 ifstream
时,我似乎收到一个错误,指出 basic_istream 移动构造函数被声明为 protected
。
istream& refToCIN ( cin ); // This is OK
const istream& refToFile = ifstream(args[1]); // This is OK
const istream& inStream ( FileIsProvided()? ifstream(args[1]) : cin );
// This 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); // This could either be a file or cin
这样做能合理吗?我忽略了一个好的替代方案吗?
最佳答案
您的代码存在以下问题:
三元运算符的左侧是一个临时值(右值)。但是,您的右手边是左值(cin
是左值)。因此,编译器试图从 cin
中创建一个临时文件,但由于复制构造函数不可用而失败。
至于结果 - 您可以简单地将 cin 的 rdbuf()
替换为您文件的 rdbuf()
,然后在任何地方使用 cin
.
这是 OP 提出的最终解决方案:
ifstream file;
std::streambuf* old_cin_buf = cin.rdbuf(); // Store the old value
if (FileIsProvided())
{
file.open(args[1]);
old_cin_buf = cin.rdbuf(file.rdbuf()); // Replace the ReadBuffer on cin.
// Store the previous value as well.
}
// Use cin for all operations now. It will either use the File or StdIn as appropriate.
...
// Restore the original value, in case it was changed by using a file.
cin.rdbuf(old_cin_buf); // This is better be done before file object here goes out of scope
关于c++ - 初始化对 istream 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577350/