简体   繁体   English

精神气:治炭[5]

[英]Spirit Qi : rule for char [5]

I have the following structure 我有以下结构

struct MyStruct 
{
    char CODE;
    char NAME[5];
};

I make it a fusion struct 我把它做成融合结构

BOOST_FUSION_ADAPT_STRUCT
(
MyStruct,
(char, MARKET_CODE)
(char, NAME[5])
)

My grammar is implemented as follow: 我的语法实现如下:

MyStruct_parser() : ticker_parser::base_type(start)
    {
        using qi::lexeme;
        using ascii::char_;

        a_word %= lexeme[+(char_)];
        start %=  a_word >> a_word;
    }
    qi::rule<Iterator, std::string(), ascii::space_type> quoted_string;
    qi::rule<Iterator, Ticker(), ascii::space_type> start;

Unfortunately it does not compile. 不幸的是它不能编译。 Now I use std::string instead of char[5] I have no problem. 现在我使用std :: string代替char [5]我没有问题。 Can you please tell me how to tell Spirit to read char[5]? 您能告诉我如何告诉Spirit读char [5]吗?

Thank you 谢谢

You can supply custom attribute transformations using boost::spirit::traits::transform_attribute<> : 您可以使用boost::spirit::traits::transform_attribute<>提供自定义属性转换:

See it Live On Coliru or indeed Live for C++03 观看Live on ColiruLive for C ++ 03

#include <boost/spirit/include/qi.hpp>
#include <boost/array.hpp>

namespace qi = boost::spirit::qi;

typedef char name_t[5];
// typedef boost::array<char, 5> name_t;

struct MyStruct {
    char   code;
    name_t name;
};

namespace boost { namespace spirit { namespace traits {

    template <>
        struct transform_attribute<name_t, std::vector<char>, qi::domain> {
            typedef std::vector<char> type;

            static type pre(name_t&) { return {}; }

            static void post(name_t& val, type const& attr) {
                static_assert(sizeof(val)==5, "");
                assert(attr.size() == sizeof(val));

                using boost::begin;
                using boost::end;
                std::copy(attr.begin(), attr.end(), begin(val));
            }
            static void fail(name_t&) { }
        };

} } }

int main()
{
    std::string const input("123456");

    using It = std::string::const_iterator;
    It f(input.begin()), l(input.end());

    MyStruct data;
    qi::rule<It, std::vector<char>()> c5 = qi::repeat(5) [ qi::char_ ];
    bool ok = qi::parse(f,l, qi::char_ >> c5, data.code, data.name);

    if (ok)
    {
        std::cout << "Parse success: " << data.code << ", '" << std::string(std::begin(data.name), std::end(data.name)) << "'\n";
    } else
    {
        std::cout << "Parse failed\n";
    }

    if (f!=l)
    {
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
    }
}

Prints 打印

Parse success: 1, '23456'

in both the c++11 and c++03 versions 在c ++ 11和c ++ 03版本中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM