Returning ifstream in a function

后端 未结 4 2148
日久生厌
日久生厌 2021-02-13 11:13

Here\'s probably a very noobish question for you: How (if at all possible) can I return an ifstream from a function?

Basically, I need to obtain the filename of a databa

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 11:38

    As an option, ifstream may be extended and custom constructor added to new class.

    I've extended it to create test resource stream, encapsulating test resource lookup inside of it.

    // test_utils.h
    class TestResourceStream : public std::ifstream {
        public:
            TestResourceStream(const char* file_path);
    };
    
    // test_utils.cpp
    namespace fs = std::filesystem;
    fs::path test_resource_path(const char* file_path) {
        fs::path path{std::string{"tests/resources/"} + file_path};
        if (!fs::exists(path))
            throw std::runtime_error{std::string{"path "} + 
                fs::absolute(path).c_str() + " does not exist"};
        return path;
    }
    TestResourceStream::TestResourceStream(const char* file_path)
        :std::ifstream{test_resource_path(file_path).c_str()} {}
    
    // usage in test
    TEST_CASE("parse") {
        std::list expertises;
        TestResourceStream stream("requests/page_response.json");
        GosDump::Json::parse(expertises, stream);
        REQUIRE(10 == expertises.size());
    }
    

提交回复
热议问题