0

I want to work with file streams generically. That is, i want to 'program to an interface and not the implementation'. Something like this:

 ios * genericFileIO = new ifstream("src.txt"); getline(genericFileIO, someStringObject);//from the string library; dont want to use C strings genericFileIO = new ofstream("dest.txt"); genericFileIO -> operator<<(someStringObject); 

Is it possible? I am not great with inheritance. Given the io class hierarchy, how do i implement what i want?

2
  • you want to implement your own stream class hierarchy or you want to figure out how to use C++ stream classes? Commented May 11, 2011 at 6:05
  • 1
    I though the C++ stream classes were interfaces. Commented May 11, 2011 at 7:26

2 Answers 2

2

Do you mean:

void pass_a_line(std::istream& in, std::ostream& out) { // error handling left as an exercise std::string line; std::getline(in, line); out << line; } 

This can work with anything that is an std::istream and std::ostream, like so:

// from a file to cout // no need to new std::ifstream in("src.txt"); pass_a_line(in, std::cout); // from a stringstream to a file std::istringstream stream("Hi"); std::ofstream out("dest.txt"); pass_a_line(stream, out); 

This does what your example do, and is programmed against the std::istream and std::ostream interfaces. But that's not generic programming; that's object oriented programming.

Boost.Iostreams can adapt classes to std::[i|o|io]streams, and does this using generic programming.

Sign up to request clarification or add additional context in comments.

2 Comments

Thats ok. Clever use of a generic function. But what i really want to do is something like in the question. Program to an interface. I mean given the io class hierarchy, shouldn't it be possible to do so?
@Abhi It's not a generic function, and one of the use of std::istream and std::ostream is to be a base class. In my function, they are considered interfaces.
1

You can use different specialisations of the ostream or istream concepts over the ostream or istream interface.

void Write(std::ostream& os, const std::string& s) { os << "Write: " << s; } std::string Read(std::istream& is) { std::string s; is >> s; return s; } int main() { Write(std::cout, "Hello World"); std::ofstream ofs("file.txt"); if (ofs.good()) Write(ofs, "Hello World"); std::stringstream ss; Write(ss, "StringStream"); Write(std::cout, ss.str()); std::string s = Read(std::cin); Write(std::cout, s); return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.