Anonymous
Anonymous

Reputation: 273

Convert ifstream to istream

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 task.

std::istream & inputStr = std::cin;
  std::ostream & outputStr = std::cout;
  if(argc == 3){
    std::fstream inputFile;
    inputFile.open(argv[1], std::fstream::in);
    if(!inputFile){
        std::cerr << "Error opening input file";
        exit(1);
    }
    inputStr = inputFile;
.....
}

Upvotes: 18

Views: 36854

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145359

No cast is necessary.

#include <fstream>
int main()
{
    using namespace std;
    ifstream    f;
    istream&    s   = f;
}

Upvotes: 32

Neil
Neil

Reputation: 5780

std::istream *istreamObj = dynamic_cast<std::istream *>(&ifStreamObj)

Upvotes: -1

Steve Guidi
Steve Guidi

Reputation: 20200

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);

Upvotes: 2

Related Questions