如何将通用文件流作为参数传递?

时间:2013-11-24 07:43:51

标签: c++ stream fstream

我有这个功能:

void check_open (ifstream& file)
{
    if (not file.is_open())
    {
        cout << "Error." << endl;
        exit(1);
    }
}

但我只能传递ifstream参数,我怎么能让它接受ofstream参数?

4 个答案:

答案 0 :(得分:5)

只要该流有is_open()方法,下面的函数就可以正常工作(fstreamifstreamofstream,并且它们的变体具有不同的字符类型)。

template<typename stream_type>
void check_open (const stream_type& file)
{
    if (not file.is_open())
    {
        cout << "Error." << endl;
        exit(1);
    }
}

答案 1 :(得分:1)

接受(引用)这些类的公共基类应该可以解决问题。

void check_open (std::ios &file)
{
    // ...
}

答案 2 :(得分:0)

尝试激动人心的涉足模板领域:

template<typename F>
void check_open (F& file)
{
    if (not file.is_open())
    {
        cout << "Error." << endl;
        exit(1);
    }
}

答案 3 :(得分:-1)

仅传递函数中的文件名,并在函数内使用ifstreamofstream