使用 boost metaparse 字符串解析包含的文件

Parse included file with boost metaparse string

我想在编译时使用 boost Metaparse 来解析 DSL。但是出于分离的考虑,我不想将我的 DSL 作为一个大字符写入 C++ 文件,而是使用预处理器,可能通过 #include,在编译时从一个单独的文件中获取文本。

boost 元解析文档提到预处理器宏 BOOST_METAPARSE_STRING 因此 BOOST_METAPARSE_STRING("DSL content") 在预处理器时转换为 metaparse::string<'D','S','L',' ', 'c','o'...>

所以不用

using input = BOOST_METAPARSE_STRING("DSL content");

我想使用类似

的东西
using input = BOOST_METAPARSE_STRING(#include "dsl.txt");

含dsl.txt含

DSL content

但是这种天真的方法行不通,有什么想法吗?

如果您不反对在包含的文件中添加一些文本,您可以将 dsl.txt 设置为:

BOOST_METAPARSE_STRING(r"//(
DSL content
)//");

然后:

using input =
#include "dsl.txt"

(假设您使用的是包含原始字符串的 C++ 版本。否则,它会更烦人。)

如果愿意,您可以使用简单的 shell 命令添加第一行和最后一行。

这并不理想,但由于 BOOST_METAPARSE_STRING 似乎需要字符串文字,我认为没有更好的选择。


另一方面,如果您发现使用外部预处理器是可以接受的,那么编写一个从文本文件创建 metaparse::string 模板调用的预处理器一点也不难。您不必将自己局限于 C++ 预处理器。任何构建工具都允许您使用自定义构建步骤;甚至首先编译预处理器以预处理文本文件。

这目前不可能; #include 一个可以直接在程序中使用的形式的任意文件,有必要对文件进行预处理,例如通过将其包装在原始字符串文字中,或使用 xxd.

(相关)论文 P1040 std::embed and P1967 Preprocessor embed (aka #embed) aim to add such a facility to C++ and to the C preprocessor respectively. If the paper is accepted, it could enter the language by C++23. In the interim, https://github.com/ThePhD/embed has patches for gcc and clang; if you are interested in exploring the feature, http://godbolt.org 有 gcc 和 clang trunk 版本,带有 std::embed 补丁可供在线使用。