1

パラメータに従って出力を出力する関数を作成したいと思います。
たとえば、ofstreamポインターを渡すと、出力がそれぞれのファイルに出力されますが、coutなどを渡すと、端末に出力されます。

ありがとう :)

4

3 に答える 3

3
void display(std::ostream& stream)
{
    stream << "Hello, World!";
}

...

display(cout);

std::ofstream fout("test.txt");
display(fout);
于 2012-05-04T17:37:02.403 に答える
2
template<typename CharT, typename TraitsT>
void print(std::basic_ostream<CharT, TraitsT>& os)
{
    // write to os
}

これにより、任意のストリームに書き込むことができます(狭いまたは広い、カスタム特性を許可します)。

于 2012-05-04T17:36:22.103 に答える
1

これはそれを行う必要があります:

template<class T>
std::ostream &output_something(std::ostream &out_stream, const T &value) {
    return out_stream << value;
}

次に、次のように使用します。

ofstream out_file("some_file");
output_something(out_file, "bleh");  // prints to "some_file"
output_something(std::cout, "bleh"); // prints to stdout
于 2012-05-04T17:35:54.867 に答える