如何比较两个std::istream引用?

时间:2022-06-06 12:36:55

I am switching over compilers from GCC to Clang/LLVM and running into compilation errors I didn't experience before.

我正在将编译器从GCC切换到Clang/LLVM,并遇到以前没有遇到过的编译错误。

I have a class that looks something like this:

我有一个类看起来是这样的:

#include <iostream>

class foo {
    public:
        bar(std::istream& is) : _fp(is), _sCheck(is != std::cin) { /* ... */ }
    private:
        std::istream& _fp;
        bool _sCheck;
}

When I compile this file, I get the following error with clang++, where the initialization of the private variable _sCheck fails:

当我编译这个文件时,我得到了clang++的以下错误,其中私有变量_sCheck的初始化失败:

error: invalid operands to binary expression ('std::istream' (aka 
'basic_istream<char>') and 'istream' (aka 'basic_istream<char>'))

  (is != std::cin)
   ~~ ^  ~~~~~~~~

If both objects in this address comparison are of the same type, why is clang++ returning an error, while g++ does not?

如果这个地址比较中的两个对象都是相同的类型,为什么clang++返回一个错误,而g++ +不返回?

I tried a dynamic_cast to make them both std::istream&, but this, too, returned an error:

我尝试了一个dynamic_cast让它们都是std::istream&,但是这个也返回了一个错误:

error: invalid operands to binary expression ('std::istream' (aka 
'basic_istream<char>') and 'std::istream')

(is != dynamic_cast<std::istream&>(std::cin))
 ~~ ^  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I apologize in advance if this is a dumb question; I appreciate any pointers.

如果这是一个愚蠢的问题,我提前道歉;我很欣赏任何指针。

1 个解决方案

#1


7  

You are using references, so you are comparing the objects and not the pointers as you maybe intended to. It seems GCC has an extension which allows you to compare std::istream objects, but this is not part of the standardized interface of std::basic_istream. Try:

您正在使用引用,所以您正在比较对象,而不是您可能想要的指针。似乎GCC有一个扩展允许您比较std::istream对象,但是这不是std: basic_istream的标准化接口的一部分。试一试:

_sCheck(&is != &std::cin)

#1


7  

You are using references, so you are comparing the objects and not the pointers as you maybe intended to. It seems GCC has an extension which allows you to compare std::istream objects, but this is not part of the standardized interface of std::basic_istream. Try:

您正在使用引用,所以您正在比较对象,而不是您可能想要的指针。似乎GCC有一个扩展允许您比较std::istream对象,但是这不是std: basic_istream的标准化接口的一部分。试一试:

_sCheck(&is != &std::cin)