How to compare two std::istream references?

瘦欲@ 提交于 2019-12-11 03:07:41

问题


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)


来源:https://stackoverflow.com/questions/18868060/how-to-compare-two-stdistream-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!