在 Boost.Spirit 中,可以使用 boost::spirit::qi::construct 函数来将解析出的结果生成为指定的结构类型。

boost::spirit::qi::construct 函数是一个函数对象,它接受一个类型参数和一个值参数,并返回一个使用类型参数和值参数构造的对象。在语法规则中,可以使用 boost::spirit::qi::as<>() 指令来将解析结果应用于 boost::spirit::qi::construct 函数。

下面是一个简单的示例,演示了如何使用 boost::spirit::qi::construct 来生成指定的结构类型:

#include <iostream>
#include <string>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

struct Person {
    std::string name;
    int age;
};

template <typename Iterator>
struct PersonGrammar : qi::grammar<Iterator, Person(), qi::space_type> {
    PersonGrammar() : PersonGrammar::base_type(start) {
        using namespace qi;

        name = +alpha;
        age = int_;

        start = name >> age;

        // 使用 construct 生成 Person 对象
        start = as<Person>() [ construct<Person>(name, age) ];
    }

    qi::rule<Iterator, std::string(), qi::space_type> name;
    qi::rule<Iterator, int(), qi::space_type> age;
    qi::rule<Iterator, Person(), qi::space_type> start;
};

int main() {
    std::string input = "John 25";
    std::string::iterator it = input.begin();
    std::string::iterator end = input.end();

    PersonGrammar<std::string::iterator> grammar;
    Person person;

    bool success = qi::phrase_parse(it, end, grammar, qi::space, person);

    if (success && it == end) {
        std::cout << "Name: " << person.name << std::endl;
        std::cout << "Age: " << person.age << std::endl;
    } else {
        std::cout << "Parsing failed" << std::endl;
    }

    return 0;
}

在上面的示例中,Person 结构包含一个 name 成员和一个 age 成员。PersonGrammar 定义了一个语法规则 start,它将解析的结果生成为 Person 类型。在 start 规则中,使用 as<Person>() 指令将解析结果应用于 construct<Person>(name, age),以生成 Person 对象。

运行上述代码,输出将会是:

Name: John
Age: 25
Boost.Spirit 使用 construct 生成指定结构类型解析结果

原文地址: https://www.cveoy.top/t/topic/jjNE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录