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

how to pass a generic file stream as a parameter?

本文关键字:参数传递 文件      更新时间:2023-10-16

我有这个函数:

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

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

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

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

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