相关疑难解决方法(0)

为什么std :: istringstream似乎在三元(?:)运算符中以不同的方式解析为std :: ifstream?

我习惯于编写带有文件名或读取的小命令行工具std::cin,所以我一直在使用这种模式:

int main(int argc, char* argv[])
{
    std::string filename;

    // args processing ...

    std::ifstream ifs;

    if(!filename.empty())
        ifs.open(filename);

    std::istream& is = ifs.is_open() ? ifs : std::cin;

    std::string line;
    while(std::getline(is, line))
    {
        // process line...
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在阅读Stack Overflow上的一个问题之后,我尝试修改我常用的模式,以满足从文件或文件中读取的需要std::istringstream.令我惊讶的是它不会编译并给出这个错误:

temp.cpp:164:47: error: invalid initialization of non-const reference of type ‘std::istream& {aka std::basic_istream<char>&}’ from an rvalue of type ‘void*’
      std::istream& is = ifs.is_open() ? ifs : iss; // won't compile
Run Code Online (Sandbox Code Playgroud)

在我看来,它试图将std::istringstreamobject(iss)转换为布尔值并获取它operator void*(). …

c++ conditional-operator c++11

25
推荐指数
3
解决办法
2292
查看次数

标签 统计

c++ ×1

c++11 ×1

conditional-operator ×1