如何设置结构体成员。
选项1 (phx::bind
)
给定一个结构体S
struct S
{
int field1;
std::string field2;
int target_field;
bool field3;
};
您可以分配给一个字段(例如target_field
)像这样:
rule<It, S()> p = int_ [ phx::bind(&S::target_field, _val) = _1 ];
现在,您可以使bind
更具可读性,通过执行以下操作:
auto target_field_ = phx::bind(&S::target_field, _val);
p = int_ [ target_field_ = _1 ];
概念证明:住在科利鲁 http://coliru.stacked-crooked.com/a/26e44f9449145141
#include "boost/spirit/include/qi.hpp"
#include "boost/spirit/include/phoenix.hpp"
namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;
typedef std::string::const_iterator It;
struct S
{
int field1;
std::string field2;
int target_field;
bool field3;
};
int main()
{
const std::string input("42");
It f(begin(input)), l(end(input));
S instance;
using namespace qi;
rule<It, S()> p = int_ [ phx::bind(&S::target_field, _val) = _1 ];
// or, alternatively:
auto target_field_ = phx::bind(&S::target_field, _val);
p = int_ [ target_field_ = _1 ];
if (parse(f, l, p, instance))
std::cout << "Parsed: " << instance.target_field;
}
选项 2(融合序列)
您可以使用以下方法将结构视为融合序列适应:
#include "boost/fusion/adapted/struct.hpp"
BOOST_FUSION_ADAPT_STRUCT(S, (int, field1)(std::string, field2)(int, target_field)(bool, field3))
现在你可以使用凤凰了lazy在语义动作中对这些序列起作用:
rule<It, S()> p = int_ [ phx::at_c<2>(_val) = _1 ];
我不喜欢这种风格(因为它将一个富有表现力的结构“降级”为……某种元组),但它可能会派上用场。住在科利鲁 http://coliru.stacked-crooked.com/a/eaa27e9cb23e0136