gpt4 book ai didi

c++ - 灵气 : rule for char [5]

转载 作者:行者123 更新时间:2023-11-30 04:03:20 27 4
gpt4 key购买 nike

我有以下结构

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

我把它做成一个 fusion 结构

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

我的语法实现如下:

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;

不幸的是它没有编译。现在我使用 std::string 而不是 char[5] 我没有问题。你能告诉我如何让 Spirit 读取 char[5] 吗?

谢谢

最佳答案

您可以使用 boost::spirit::traits::transform_attribute<> 提供自定义属性转换:

看到它 Live On Coliru 或者确实是 Live 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";
}
}

打印

Parse success: 1, '23456'

在 c++11 和 c++03 版本中

关于c++ - 灵气 : rule for char [5],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24493589/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com