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