How to compare two std::istream references?

2019-07-18 15:16发布

问题:

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

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:

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?

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

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:

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:

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