用错误检查初始化ifstream的类成员初始化器

Class member initializer to initialize ifstream with error check?

本文关键字:初始化 成员 ifstream 错误 检查      更新时间:2023-10-16

我正在尝试使用c++ 11的类成员初始化器功能来初始化类的变量。类的变量是std::string和std::ifstream。

class A{
    std::string filename = "f1.txt";
    std::ifstream filestream = ....
public:
    ....
};

是否有一种方法可以在初始化文件流的同时使用类成员初始化来检查错误?

我想做的是,类似于下面的内容:

class A{
    std::string filename = "f1.txt";
    std::ifstream filestream(filename);
    if(filestream.is_open()) .... // check if file cannot be opened
public:
    ....
};

您可以编写并调用内联lambda表达式来执行适当的检查;这样的lambda表达式可以访问数据成员:

class A {
    std::string filename = "f1.txt";
    std::ifstream filestream = [&] {
        std::ifstream fs{filename};
        if (!fs)
            throw std::runtime_error("failed to open ifstream");
        return fs;
    }();
};

将逻辑分离成一个可重用的辅助函数(以filename为参数)可能会更清楚,例如一个静态成员函数:

class A {
    std::string filename = "f1.txt";
    std::ifstream filestream = openChecked(filename);
    static std::ifstream openChecked(std::string const& filename)
    {
        std::ifstream fs{filename};
        if (!fs)
            throw std::runtime_error("failed to open ifstream");
        return fs;
    }
};