パラメータに従って出力を出力する関数を作成したいと思います。
たとえば、ofstreamポインターを渡すと、出力がそれぞれのファイルに出力されますが、coutなどを渡すと、端末に出力されます。
ありがとう :)
パラメータに従って出力を出力する関数を作成したいと思います。
たとえば、ofstreamポインターを渡すと、出力がそれぞれのファイルに出力されますが、coutなどを渡すと、端末に出力されます。
ありがとう :)
void display(std::ostream& stream)
{
stream << "Hello, World!";
}
...
display(cout);
std::ofstream fout("test.txt");
display(fout);
template<typename CharT, typename TraitsT>
void print(std::basic_ostream<CharT, TraitsT>& os)
{
// write to os
}
これにより、任意のストリームに書き込むことができます(狭いまたは広い、カスタム特性を許可します)。
これはそれを行う必要があります:
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