1

I want to create a function, that prints output according to its parameter.
Like if I pass a ofstream pointer it should print the output to the respective file, whereas if i pass cout or something, that makes it print to the terminal.

Thanks :)

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 回答