solti solti - 2 months ago 23
C++ Question

Class member initializer to initialize ifstream with error check?

I am trying to use C++11 feature of class member initializer to initialize variables of class. The variables of class that I have are std::string and std::ifstream.

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


Is there any way to initialize filestream and also check for error at the same time using class member initialization.

What I want to do is, something similar to below :

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

Answer

You can write and call an inline lambda-expression that performs the appropriate checks; such a lambda-expression has access to the data members:

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

It may be clearer to separate out the logic into a reusable helper function taking filename as a parameter, e.g. a static member function:

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