在编译时读取文件(constexpr 或其他)
Read File At Compile Time (constexpr or other)
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");
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 多成员Constexpr结构初始化
- 条件constexpr函数
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- Visual C++ constexpr Hints
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在其他文件中创建类时在 c++ 项目中不起作用
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 类与私有变量的其他类之间的线程安全性
- 为什么constexpr的性能比正常表达式差
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 如果有 constexpr if 语句,为什么没有其他 constexpr 语句呢?
- 在编译时读取文件(constexpr 或其他)
- C++constexpr数组查找:内存开销?其他问题
- 将一个 constexpr 数组初始化为其他两个 constexpr 数组的总和