在 Boost.Spirit 中,可以使用as<>和attr_cast<>来控制解析结果的类型和构造函数的参数次序。

首先,你可以使用as<>来指定解析结果的类型。例如,假设你有一个结构类型MyStruct,你可以在语法规则中使用as<MyStruct>来将解析结果转换为MyStruct类型。示例如下:

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

namespace qi = boost::spirit::qi;

struct MyStruct {
    int a;
    int b;
};

int main() {
    std::string input = "1 2";
    std::vector<MyStruct> result;

    qi::rule<std::string::iterator, MyStruct()> myRule = qi::int_ >> qi::int_;
    qi::phrase_parse(input.begin(), input.end(), myRule % qi::eol, qi::space, result);

    for (const auto& item : result) {
        std::cout << "a: " << item.a << ", b: " << item.b << std::endl;
    }

    return 0;
}

在上述示例中,myRule定义了一个规则,它将两个整数解析为一个MyStruct对象。通过使用as<MyStruct>,解析结果将转换为MyStruct类型。

如果你希望控制构造函数的参数次序,你可以使用attr_cast<>。attr_cast<>提供了一种将解析结果转换为指定类型的方法,并且可以使用任意的构造函数参数次序。示例如下:

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

namespace qi = boost::spirit::qi;

struct MyStruct {
    int a;
    int b;

    MyStruct(int a, int b) : a(a), b(b) {}
};

int main() {
    std::string input = "1 2";
    std::vector<MyStruct> result;

    qi::rule<std::string::iterator, MyStruct()> myRule = qi::int_ >> qi::int_;
    qi::phrase_parse(input.begin(), input.end(), myRule % qi::eol, qi::space, result);

    for (const auto& item : result) {
        std::cout << "a: " << item.a << ", b: " << item.b << std::endl;
    }

    return 0;
}

在上述示例中,MyStruct定义了一个自定义的构造函数,按照指定的参数次序初始化成员变量。通过使用attr_cast<>,解析结果将按照指定的参数次序传递给构造函数,从而实现控制构造函数的参数次序的目的。