c++ - 初始化对 istream 的引用

标签 c++ reference

我正在尝试编写我的程序,以便它可以处理 StdIn 或命令行上指定的文件。

我通过尝试初始化对 istream 的引用来引用 cinifstream,使用条件.

(描述了类似的技术 herehere)

但是当我尝试使用 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/

相关文章:

c++ - ReSharper C++ : Allow CString as a %s printf parameter?

c++ - 愚蠢的 C++ 引用问题

c++ - 在 Visual Studio 2010 上安装 LibCurl

c++ - 如何使用 C++ 从字符串中删除前导零?

c++ - 使用析构函数做工作

c++ - 二维数组中的 "Excess elements in scalar initializer"错误

reference - ETS创建返回值

我可以用一个函数交换两个矩阵,只交换其基地址,而不逐个元素交换吗?

PHP - 通过引用函数参数传递

c# - 在 C# 的反序列化过程中创建指向父对象的指针