INTRODUCTION
void read_foo (std::ifstream& out);
void write_foo (std::ofstream& out);
I have these two functions where one is supposed to read from a file, and the other is supposed to write to one.
Everything works having the below snippets;
std::ifstream ifs ("filename.txt");
read_foo (ifs);
std::ofstream ofs ("filename.txt");
write_foo (ofs);
THE PROBLEM
However, if I try to use a std::fstream
, so I can call both functions with the same stream, it doesn't compile, and the compiler spits out a lot of error messages.
- Why can't I bind a
fstream
to anifstream&
, orofstream&
?
foo.cpp
#include <fstream>
void read_foo (std::ifstream& out);
void write_foo (std::ofstream& out);
int main () {
std::fstream fs ("filename.txt");
read_foo (fs);
write_foo (fs);
}
Error(s):
foo.cpp: In function ‘int main()’:
foo.cpp:9:16: error: invalid initialization of reference of type ‘std::ifstream& {aka std::basic_ifstream<char>&}’ from expression of type ‘std::fstream {aka std::basic_fstream<char>}’ read_foo (fs);
^
foo.cpp:3:7: note: in passing argument 1 of ‘void read_foo(std::ifstream&)’ void read_foo (std::ifstream& out);
foo.cpp:10:16: error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream<char>&}’ from expression of type ‘std::fstream {aka std::basic_fstream<char>}’
write_foo (fs);
^
foo.cpp:4:6: note: in passing argument 1 of ‘void write_foo(std::ofstream&)’ void write_foo (std::ofstream& out);