2011-05-11 12 views
0

ファイルストリームを一般的に扱いたい。つまり、私は「実装ではなくインターフェイスにプログラムする」ことを望んでいます。このようなもの:一般的なファイルストリームの操作

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

可能でしょうか?私は相続財産ではない。 ioのクラス階層を考えると、私は何をしたいのですか?

+0

独自のストリームクラス階層を実装したい場合や、C++ストリームクラスの使い方を知りたい場合は、 –

+0

どちらか簡単です:) – badmaash

+1

私はC++ストリームクラスはインターフェイスでした。 –

答えて

2

あなたが意味するか:

// 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); 

これはあなたの例が何を行い、そしてstd::istreamに対してプログラムされている:ので、同じよう

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

これは、std::istreamstd::ostreamあるものを扱うことができますおよびstd::ostreamインターフェースを含む。しかし、これは汎用プログラミングではありません。それはオブジェクト指向プログラミングです。

Boost.Iostreamsは、クラスをstd::[i|o|io]streamに適合させることができ、これは汎用プログラミングを使用して行います。

+0

本当にありがとうございます。ジェネリック関数の賢明な使用。しかし、私が本当にやりたいことは、質問のようなものです。インターフェイスへのプログラム。私はioのクラス階層を与えられていることを意味します、そうすることはできませんか? – badmaash

+1

@Abhiこれは汎用関数ではなく、 'std :: istream'と' std :: ostream'を使うのは基本クラスです。私の機能では、インタフェースと見なされます*。 –

1

ostreamまたはistreamインターフェイスで、ostreamまたはistreamのさまざまな特殊化を使用できます。

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; 
} 
関連する問題