c++ - 基于条件的 Istream 引用

标签 c++

我应该如何在 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<_Elem, _Traits>::basic_istream(std::basic_istream<_Elem, _Traits>::_Myt &&_Right) [with _Elem=char, _Traits=std::char_traits]" (declared at line 55 of "d:\Program Files\Visual Studio 2017\VC\Tools\MSVC\14.11.25503\include\istream") is inaccessible

最佳答案

您不能将临时变量绑定(bind)到您的非常量 引用。您必须创建一个真正的变量并绑定(bind)它:

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;

关于c++ - 基于条件的 Istream 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848297/

相关文章:

C++ - 如何获取结构的最后一个成员类型以及从现有对象访问它的方法?

c++ - 避免与 Bullet 发生地面碰撞

c++ - 处理 tcp/udp 接收的最佳方式。

c++ - 模板结构的静态常量成员的不同值

c++ - 带线程的 fork 和 core dump

c++ - 实现 is_constexpr_copiable

c++ - 如何根据标记的参数包调用一组可 rebase 类构造函数?

c++ - QML:如何将着色器效果与 QtGraphical 效果混合?

c++ - 如何将函数变量传递给 C++ lambda 函数

c# - PInvoke 致命执行引擎错误