-1

Is there any way I can convert an ifstream to an istream? I have a function called getToken(istream* br) that accepts an istream as the parameter, but within my main() I use an ifstream to read a file, and I must use this same ifstream to call getToken. How can I overcome this issue?

jww
  • 97,681
  • 90
  • 411
  • 885
  • 1
    You don't need to it is *already* an `ìstream` – Galik Oct 18 '17 at 02:19
  • `ifstream` is derived from `istream`. You should be able to just pass it to `getToken`. What happens when you try? Show a [mcve] – Igor Tandetnik Oct 18 '17 at 02:19
  • In addition to Galik's comment, you could `dynamic_cast` it if you really wanted an `istream&` or `istream*`. But its not necessary and adds additional overhead. Also see [dynamic_cast and static_cast in C++](https://stackoverflow.com/q/2253168/608639). – jww Oct 18 '17 at 05:46

1 Answers1

6

As mentioned in the comments, you don't need to do anything fancy. The std::ifstream type inherits from std::istream, so any function that takes an istream* can take a pointer to an ifstream as input. For example:

string getToken(istream* stream) {
    ...
}

ifstream fileStream;
getToken(&fileStream);

The streams classes were specifically designed to make operations like this one possible.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065