如何将通用文件流作为参数传递
how to pass a generic file stream as a parameter?
我有这个函数:
void check_open (ifstream& file)
{
if (not file.is_open())
{
cout << "Error." << endl;
exit(1);
}
}
但我只能传递ifstream参数,我怎么能让它也接受流参数呢?
只要流具有is_open()
方法,下面的函数就可以正常工作(fstream
、ifstream
、ofstream
,以及它们的不同字符类型的变体)。
template<typename stream_type>
void check_open (const stream_type& file)
{
if (not file.is_open())
{
cout << "Error." << endl;
exit(1);
}
}
接受这些类的公共基类(引用)就可以了。
void check_open (std::ios &file)
{
// ...
}
尝试一下令人兴奋的模板领域:
template<typename F>
void check_open (F& file)
{
if (not file.is_open())
{
cout << "Error." << endl;
exit(1);
}
}
只传递函数中的文件名,并在函数中使用ifstream
或ofstream
。
相关文章:
- 是否可以在命令行中将输入参数传递给可执行文件
- 如何使用输入参数作为文件的传递?
- 如果作为参数传递,请打开文件,否则打开主应用菜单
- 将文件的内容作为参数传递到C 程序中
- 如何将.txt文件作为不同 cpp 中函数的参数传递
- 将文本文件而不是用户输入作为命令行参数传递
- 为在应用程序中作为函数参数传递的文件运行'iconv'命令C++
- 使用 php 将带有命令行可执行文件路径的参数传递
- Xcode 不会将参数传递给可执行文件C++
- 将标头中定义的 MyClass 作为函数参数传递给其他文件
- 如何在C++中将文件作为参数传递
- C++:如何将参数传递给可执行文件
- 如何将通用文件流作为参数传递
- 如何在 c++ 中将数据文件作为参数传递到函数中
- 如何读取名称(仅文件.txt)作为参数传递的文件(在任何目录中)?C++
- C++ 将文件 * 作为参数传递给函数
- 如何在将函数作为参数传递给文件中.cpp函数模板时声明
- 将命令行参数输入文件传递给要分析的类
- 将文件的每一行作为命令行参数传递给二进制文件
- 在C++中将webM文件作为参数传递