无法使用三元运算符有条件地分配“istream &”?

Unable to use ternary operator to conditionally assign `istream &`?

我有一个接受 std::istream & 的构造函数,并在分配其中一个成员 (std::istream &) 之前检查它。例如:

class Stream
{
    public:
    Stream(std::istream &is) : s_ {is.good() ? is : throw std::runtime_error {"Invalid input stream\n"}} 
        {}

    private:
    std::istream &s_;
};

编译器抱怨 std::basic_istream(const basic_istream &) 的构造函数被删除(可以理解,因为您不能复制流)。但是,我看不到这里在哪里进行任何复制?它必须在三元运算符内,因为

Stream(std::istream &is) : s {is} {}

无需检查即可正常工作。试图复制的 std::istream 在哪里?我该如何解决这个问题?

这个GCC bug 64372.

来自 conditional operator, we learn that if one operands of the conditional operator is a throw-expression, "[t]he result of the conditional operator has the type and the value category of the other expression." Thus, your use of the conditional operator should result in a type of std::istream&, but GCC thinks it's std::istream 上的 cppreference。


要解决此 GCC 错误,请使用辅助函数:

class Stream
{
    public:
    Stream(std::istream &is) : s_ {validated_stream(is)} 
        {}

    private:
    std::istream &s_;

    static std::istream &validated_stream(std::istream &is) {
        if (!is.good()) throw std::runtime_error {"Invalid input stream\n"};
        return is;
    }
};