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

Read File At Compile Time (constexpr or other)

本文关键字:constexpr 其他 文件 编译 读取      更新时间:2023-10-16

C++17 是否提供在编译时加载/读取文件的方法?更具体地说,我想将文件的内容加载到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 年开始。teivaz的解决方案完美运行,使用了一些宏和#include魔法。但是,它需要更改输入文件:文件应将其内容包含在 STR( ... ( 中,这可能并不总是可行的。

由于上面的答案很老,我想也许事情已经发生了变化,也许 C++17(或可能是 C++20(提供了一些功能来克服这个问题。

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

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