基于条件的iStream引用
Istream reference based on condition
我应该如何在C 中做这样的事情?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string input_filename_ = "";
istream& input = (input_filename_ == "") ? cin : ifstream(input_filename_, ifstream::in);
我遇到了这个错误,不知道为什么。
e0330" std :: basic _istream&lt; _ elem,_traits> :: basic _istream(std :: basic_istream&lt; _traits> :: ___________________ _ myt(在" D: Program Files Visual Studio 2017 VC Tools MSVC MSVC 14.11.25503 Inclupper istream"的第55行中声明。
您无法将临时性绑定到 non-const 参考。您必须创建一个真实的变量并绑定:
ifstream ifs(input_filename, ifstream::in); // a real variable
istream& input = input_filename.empty() ? cin : ifs; // that should bind properly
通常,我做的事情与此相似,以确保用户提供了一个文件名并正确打开文件:
std::ifstream ifs;
if(!file_name.empty()) // do we have a file name?
ifs.open(file_name); // try to open it
if(!ifs) // if we tried to open it but it failed
throw std::runtime_error(std::string(std::strerror(errno)) + ": " + file_name);
// only attach file to reference if user gave a file name
std::istream& in = file_name.empty() ? std::cin : ifs;
当您使用
时istream& input = (input_filename_ == "") ? cin : ifstream(input_filename_, ifstream::in);
表达的最后一部分是暂时的。您不能使用它来初始化非const参考。
您必须对其进行稍有不同的处理。
std::ifstream str;
std::istream* str_ptr = &std::cin;
if (input_filename_ != "")
{
str.open(input_filename_);
str_ptr = &str;
}
std::istream& input = *str_ptr;
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- 为什么istream不支持右值提取
- 将无符号char*转换为std::istream*C++
- c++r值引用应用于函数指针
- C++,如何根据运行时条件构造引用不同 istream 对象的对象?
- 引用另一个类时的 iStream 重载
- 基于条件的iStream引用
- 为什么 istream 类的运算符<<在 C++ 中具有引用的返回/参数类型?
- 在C++中返回对 istream 的引用
- 为什么我们需要在重载>>和<<运算符时返回对 istream/ostream 的引用?
- 我使用 istream 获得未初始化的引用成员
- 为什么不能重新分配给对 istream / ostream 的引用
- 如何比较两个 std::istream 引用
- 使用std::istream引用初始化初始化初始化