在编译时读取文件(constexpr 或其他)

Read File At Compile Time (constexpr or other)

C++17 是否提供在编译时 load/read 文件的任何方法?更具体地说,我想将文件的内容加载到 const char*std::string_view 等中。例如:

    constexpr const char* read_file_content(const char* file_path) {
        /* should read in the content of the file and return it */
        return "";
    }

    constexpr const char* file_path    = "some/folder/file.json";
    constexpr const char* file_content = read_file_content(file_path);


我从 2014 年开始遇到这个答案 Is it possible to read a file at compile time?teivaz 的解决方案非常有效,使用了一些宏和 #include 魔法。但是,它需要更改输入文件:文件应将其内容包含在 STR( ... ) 中,这可能并非总是可行。

由于上面的答案很旧,我想也许事情已经改变了,也许 C++17(或可能是 C++20)提供了一些功能来解决这个问题。

C++20 可能会附带 std::embed。看看 P1040。如果这个落地,你可以

constexpr std::span<const std::byte> someBytes = std::embed("pathToFile");