C ++如何创建一个函数,该函数在终端和文件上打印

c++ how to create a function, that prints on terminal as well as file

本文关键字:函数 打印 文件 终端 何创建 创建 一个      更新时间:2023-10-16

我想创建一个函数,根据其参数打印输出。
就像如果我传递一个 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