C++模板化输出:iostream 或 fstream
如何模板化 iostream 和 fstream 对象?这种方式(请参阅代码)是不正确的......感谢您的帮助。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有两个问题:
要创建一个可以写入任意输出流的函数,您不需要将其设为模板。相反,让它通过引用获取 ostream 作为其参数。 ostream 是所有输出流对象的基类,因此该函数可以接受任何输出流。
iostream类是一个抽象类,不能直接实例化。它被设计为其他可以读写的流类(例如 fstream 和 stringstream)的基类。如果您想使用函数传递 cout 作为参数来打印到控制台。
希望这有帮助!
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!
尽管您的
main
函数存在一些严重错误,但您的模板函数非常适合我。修复错误后,这个程序对我有用:不过,我不确定为什么你需要一个模板函数。对于这种特殊情况,常规多态性更有意义。
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:I'm not sure why you want a template function, though. Regular polymorphism makes much more sense for this particular case.