Convert ifstream to istream

前端 未结 3 1262
礼貌的吻别
礼貌的吻别 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条回答
  •  猫巷女王i
    2020-12-20 13:09

    Try:

    std::ifstream* myStream;
    std::istream* myOtherStream = static_cast(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);
    

提交回复
热议问题