C++ templatize output: iostream or fstream
How to templatize iostream and fstream objects? This way (see the code, please) is not correct... Thanks for your help.
template <typename O>
void test(O &o)
{
o << std::showpoint << std::fixed << std::right;
o << "test";
}
int main(int argc, _TCHAR* argv[])
{
std::iostream out1; //Write into console
std::ofstream out2 ("file.txt"开发者_运维问答); //Write into file
....
test(out1);
test (out2);
return 0;
}
There are two issues here:
To make a function that can write to an arbitrary output stream, you don't need to make it a template. Instead, have it take an ostream by reference as its parameter. ostream is the base class of all output stream objects, so the function can accept any output stream.
The class iostream is an abstract class that cannot be directly instantiated. It's designed to be the base class of other stream classes tha can read and write, such as fstream and stringstream. If you want to print to the console using your function pass cout as a parameter.
Hope this helps!
Your template function works perfectly for me, although your main
function had some serious errors in it. After fixing your errors, this program works for me:
#include <iostream>
#include <fstream>
template <typename O>
void test(O &o)
{
o << std::showpoint << std::fixed << std::right;
o << "test";
}
int main(int argc, char* argv[])
{
// std::iostream out1; //Write into console
std::ofstream out2 ("file.txt"); //Write into file
// ....
test(std::cout);
test (out2);
return 0;
}
I'm not sure why you want a template function, though. Regular polymorphism makes much more sense for this particular case.
精彩评论