c++模板输出:iostream或fstream

C++ templatize output: iostream or fstream

本文关键字:iostream fstream 输出 c++      更新时间:2023-10-16

如何模板化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;
}

有两个问题:

  1. 要创建一个可以写入任意输出流的函数,您不需要将其创建为模板。相反,让它通过引用将ostream作为其参数。ostream是所有输出流对象的基类,因此该函数可以接受任何输出流。

  2. iostream是一个抽象类,不能直接实例化。它被设计成其他可以读写的流类的基类,比如fstream和stringstream。如果您想使用函数pass cout作为参数打印到控制台。

希望这对你有帮助!

你的模板函数对我来说是完美的,尽管你的main函数有一些严重的错误。修复你的错误后,这个程序为我工作:

#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;
}

我不确定为什么你想要一个模板函数。对于这种特殊情况,正则多态性更有意义。