Search code examples
c++ifstreamcindifference

C++ How to differentiate std::cin to std::ifstream?


I am trying to make a simple comparison to find if istream is a std::cin or std::ifstream.

My pseudocode is something like that:

class myclass
{
public:
    void write(istream& is)
    {
        if(is == cin) // this does not work
        {
            //do something
        }
        else
        {
            //do something else
        }
    }     
};

How can I proceed?

Thank you!


Solution

  • Since std::cin is an instance of std::istream, you could compare the addresses of the two objects to see if they are equal:

    if (&is == &std::cin)
    

    (Demo)

    However I would consider investigating if you can achieve your goal without doing this; switching logic based on the identity of the stream argument is not very clean and may inhibit future development or maintenance of this project.