rub*_*nvb 6 c++ boost boost-spirit c++14 boost-spirit-x3
我正在尝试将LaTeX转义码(例如\alpha)解析为Unicode(数学)字符(即U+1D6FC).
现在这意味着我正在使用这个symbols解析器(规则):
struct greek_lower_case_letters_ : x3::symbols<char32_t>
{
greek_lower_case_letters_::greek_lower_case_letters_()
{
add("alpha", U'\u03B1');
}
} greek_lower_case_letter;
Run Code Online (Sandbox Code Playgroud)
这很好,但意味着我得到了std::u32string一个结果.我想要一种优雅的方法来保持代码中的Unicode代码点(可能是未来的自动化)和维护原因.有没有办法让这种解析器解析为UTF-8 std::string?
我想过将symbolsstruct解析为a std::string,但这样效率非常低(我知道,早期优化bla bla).
我希望有一些优雅的方式,而不是通过一堆箍来使这工作(symbols将结果附加到字符串).
我担心使用代码点值并想要UTF8会产生转换的运行时成本(或者是否有constexprUTF32-> UTF8转换?).
cierelabs上的JSON解析器示例显示了一种使用语义操作以utf8编码附加代码点的方法:
auto push_utf8 = [](auto& ctx)
{
typedef std::back_insert_iterator<std::string> insert_iter;
insert_iter out_iter(_val(ctx));
boost::utf8_output_iterator<insert_iter> utf8_iter(out_iter);
*utf8_iter++ = _attr(ctx);
};
// ...
auto const escape =
('u' > hex4) [push_utf8]
| char_("\"\\/bfnrt") [push_esc]
;
Run Code Online (Sandbox Code Playgroud)
这用于他们的
typedef x3::rule<unicode_string_class, std::string> unicode_string_type;
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,将utf8序列构建到std::string属性中.
有关完整代码,请参阅:https://github.com/cierelabs/json_spirit/blob/x3_devel/ciere/json/parser/x3_grammar_def.hpp