有几种方法可以给这只猫剥皮:
- 您可能考虑推迟执行绑定表达:
phx::bind
可以做到这一点
- 或者,你可以使用属性传播为此(并且不做语义动作共)
- 最后,你可以使用继承属性(例如,当 DataContext 没有默认构造函数或者复制成本很高)
1. 推迟与凤凰的束缚
使用phoenix bind达到目的:这将产生一个Phoenix actor,它将在执行时“延迟执行”语义动作被触发。
以下是您可能需要的缺失代码示例的重建:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace phx= boost::phoenix;
struct DataContext
{
double xy;
};
template <typename Iterator, typename Skipper>
struct my_grammar : qi::grammar<Iterator, Skipper>
{
my_grammar(DataContext& dataContext) : my_grammar::base_type(start)
{
start = qi::double_
[ phx::bind(&my_grammar::newValueForXY,
phx::ref(dataContext),
qi::_1) ];
}
private:
static void newValueForXY(DataContext& dc, double value)
{
dc.xy = value;
}
qi::rule<Iterator, Skipper> start;
};
int main()
{
const std::string s = "3.14";
DataContext ctx;
my_grammar<decltype(begin(s)), qi::space_type> p(ctx);
auto f(begin(s)), l(end(s));
if (qi::phrase_parse(f, l, p, qi::space))
std::cout << "Success: " << ctx.xy << "\n";
}
Note:
- phx::ref() 将引用包装到数据上下文
- qi::_1 而不是 boost::_1 作为占位符
-
鉴于此实施newValueForXY
你可以很容易地写
start = qi::double_
[ phx::bind(&DataContext::xy, phx::ref(dataContext)) = qi::_1 ];
2. 使用属性语法,而不是语义动作
但是,我可能会使用属性而不是语义操作来编写相同的示例(因为这基本上就是他们是为了):
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace phx= boost::phoenix;
struct DataContext {
double xy;
};
BOOST_FUSION_ADAPT_STRUCT(DataContext, (double, xy))
template <typename Iterator, typename Skipper>
struct my_grammar : qi::grammar<Iterator, DataContext(), Skipper>
{
my_grammar() : my_grammar::base_type(start) {
start = qi::double_;
}
private:
qi::rule<Iterator, DataContext(), Skipper> start;
};
int main()
{
const std::string s = "3.14";
static const my_grammar<decltype(begin(s)), qi::space_type> p;
DataContext ctx;
if (qi::phrase_parse(begin(s), end(s), p, qi::space, ctx))
std::cout << "Success: " << ctx.xy << "\n";
}
3.使用继承属性传入上下文引用
如果你绝对坚持,你甚至可以使用inherited attributes
为目的:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace phx= boost::phoenix;
struct DataContext {
double xy;
};
template <typename Iterator, typename Skipper>
struct my_grammar : qi::grammar<Iterator, void(DataContext&), Skipper> {
my_grammar() : my_grammar::base_type(start)
{
start = qi::double_ [ phx::bind(&DataContext::xy, qi::_r1) = qi::_1 ];
}
qi::rule<Iterator, void(DataContext&), Skipper> start;
};
int main() {
const std::string s = "3.14";
const static my_grammar<std::string::const_iterator, qi::space_type> p;
DataContext ctx;
if(qi::phrase_parse(begin(s), end(s), p(phx::ref(ctx)), qi::space)) {
std::cout << "Success: " << ctx.xy << "\n";
}
}
这在调用站点上更具表现力:
qi::phrase_parse(begin(s), end(s), p(phx::ref(ctx)), qi::space));
并且不要求上下文是默认可构造的。