1

如果我们忽略该属性,这test::char_将起作用。

namespace test {
    struct any_char: x3::char_parser<any_char> {
        static bool const has_attribute = false;
        template <typename Char, typename Context>
        bool test(Char ch_, Context const&) const {
            return true;
        }
    };

    auto const char_ = any_char{};
}

但是如果我们想从中获取属性test::char_呢?我不知道如何正确设置属性类型,因为这个属性类型应该是

typename std::iterator_traits<Iterator>::value_type

这在精神 qi 中不是问题,因为 qi 解析器有一个模板属性结构,我们可以在其中从 Iterator 获取 char 类型。

编辑:谢谢你回答这个问题。自动属性传播适用于test::char_,但它仍然不能传播正确的属性,例如复合属性+test::char_

Edit2:我想用这个 test::char_ 来替换 x3 中的各种 char_encoding::char_。例如我有一个简单的解析器函数 foo。输入字符串可以是 ascii 编码字符串或宽字符编码字符串。因此,我可以在任何地方使用这个 test::char_ 而不是 x3::char_ 和 x3::standard_wide::char_ 和 #IFDEF。

#ifdef NARROW_CHAR
    using _char = char;
    #define _STR(str) str
#else
    using _char = wchar_t;
    #define _STR(str) L ## str
#endif

bool foo(std::basic_string<_char> const& input, std::basic_string<_char>& attr) {
    return x3::parse(
        input.begin(),
        input.end(), 
        +(test::char_ - _STR('X')),
        attr);
}

Edit3:将 attribute_type 设置为 void 或 x3::unused_type 将使 test::char_ 传播正确的属性。

namespace test {
    struct any_char: x3::char_parser<any_char> {
        using attribute_type = void; // or x3::unused_type
        static bool const has_attribute = true;
        template <typename Char, typename Context>
        bool test(Char ch_, Context const&) const {
            return true;
        }
    };

    auto const char_ = any_char{};
}

Edit4:与此测试相比,来自 sehe 的 http://coliru.stacked-crooked.com/a/0a487591fbaedef4 可能是一个更好的主意:: char_ 谢谢。

4

1 回答 1

4

自动属性传播已经解决了它:

Live On Coliru

#include <boost/spirit/home/x3.hpp>
#include <string>
#include <iostream>
#include <iostream>
using namespace std::string_literals;
namespace x3 = boost::spirit::x3;

namespace test {
    struct any_char: x3::char_parser<any_char> {
        static bool const has_attribute = false;
        template <typename Char, typename Context>
        bool test(Char /*ch_*/, Context const&) const {
            return true;
        }
    };

    auto const char_ = any_char{};
}

template <typename S>
void doTest(S const& s) {

    typename S::value_type ch;

    if (x3::parse(s.begin(), s.end(), test::char_, ch)) {
        std::wcout << L"Parsed: " << std::wcout.widen(ch) << std::endl;
    } else {
        std::wcout << L"Not parsed\n";
    }

}

int main() {
    doTest("Hello"s);
    doTest(L"World"s);
}

印刷

Parsed: H
Parsed: W
于 2017-03-21T15:00:07.897 回答