c++模板输出:iostream或fstream
C++ templatize output: iostream or 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;
}
有两个问题:
-
要创建一个可以写入任意输出流的函数,您不需要将其创建为模板。相反,让它通过引用将ostream作为其参数。ostream是所有输出流对象的基类,因此该函数可以接受任何输出流。
-
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;
}
我不确定为什么你想要一个模板函数。对于这种特殊情况,正则多态性更有意义。
相关文章:
- 在fstream期间忽略空行
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话
- 需要从 istream 和 ostream 派生 iostream
- 使用fstream对txt文件中的数字进行循环
- std::带有自定义缓冲区的 iostream 不允许我写入
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 使 std::fstream 写入文件末尾,但从头开始读取
- 新的放置取决于 iostream
- 包含在 <initializer_list> <iostream>?
- 为什么在包含iostream时可以使用printf()?
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 如果 iostream 对象不可复制,为什么以下代码是合法的?
- iostream 和 fstream 的重载<<
- fstream,ofstream,ostream,iostream之间的区别
- 仅使用 <iostream>、 <fstream> 和 <cstdlib>清除字符串中的任何多余空格
- 为什么同时包含<iostream>和<fstream>
- Ubuntu 13.10 中的 GCC iostream fstream 错误
- c++模板输出:iostream或fstream