开发者

Working with file streams generically

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?


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜