Convert ifstream to istream

前端 未结 3 1236
礼貌的吻别
礼貌的吻别 2020-12-20 12:43

How would one go about casting a ifstream into a istream. I figure since ifstream is a child of istream I should be able to do so but I have been having problems with such a

相关标签:
3条回答
  • 2020-12-20 13:09

    Try:

    std::ifstream* myStream;
    std::istream* myOtherStream = static_cast<std::istream*>(myStream);
    myOtherStream = myStream;   // implicit cast since types are related.
    

    The same works if you have a reference (&) to the stream type as well. static_cast is preferred in this case as the cast is done at compile-time, allowing the compiler to report an error if the cast is not possible (i.e. istream were not a base type of ifstream).

    Additionally, and you probably already know this, you can pass a pointer/reference to an ifstream to any function accepting a pointer/reference to a istream. For example, the following is allowed by the language:

    void processStream(const std::istream& stream);
    
    std::ifstream* myStream;
    processStream(*myStream);
    
    0 讨论(0)
  • 2020-12-20 13:10
    std::istream *istreamObj = dynamic_cast<std::istream *>(&ifStreamObj)
    
    0 讨论(0)
  • 2020-12-20 13:15

    No cast is necessary.

    #include <fstream>
    int main()
    {
        using namespace std;
        ifstream    f;
        istream&    s   = f;
    }
    
    0 讨论(0)
提交回复
热议问题