Working with file streams generically

谁说胖子不能爱 提交于 2020-01-06 05:22:20

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/5959832/working-with-file-streams-generically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!