【问题标题】:Token parser semantic action令牌解析器语义动作
【发布时间】:2011-07-25 14:43:12
【问题描述】:

我已经根据spirit lex example 4 中显示的代码编写了一个工作令牌解析器

我的一条规则如下所示

    set_name 
        =   (   tok.set_ >> tok.name_ >> tok.identifier )
            [
                std::cout << val("set name statement to: ") << _3 << "\n"
            ]
        ;

这很好用。当出现

SET NAME xyz

它按我的预期输出

设置名称语句为:xyz

现在我想做一些有用的事情,将找到的名称存储到一个类中。在parser semantic examples工作,我写了这段代码

  class writer
    {
    public:
        void print(string const& s) const
        {
            std::cout << s << std::endl;
        }
    };

  writer w;

  ...

    set_name 
        =   (   tok.set_ >> tok.name_ >> tok.identifier )
            [
                boost::bind( &writer::print, &w, ::_3 )
            ]
        ;

这不会编译

1>C:\Program Files\boost\boost_1_44\boost/bind/bind.hpp(318) : 错误 C2664: 'R boost::_mfi::cmf1::operator ()(const U &,A1) const' :无法将参数 2 从 'bool' 转换为 'const std::basic_string' 1> 与 1> [ 1> R=空, 1> T=eCrew::rule::writer, 1> A1=const std::string &, 1> U=eCrew::rule::writer * 1>] 1> 和 1> [ 1> _Elem=字符, 1> _Traits=std::char_traits, 1> _Ax=std::分配器 1>] 1> 原因:无法从 'bool' 转换为 'const std::string' 1> 没有构造函数可以采用源类型,或者构造函数重载决议不明确

为什么编译器会抱怨试图从 bool 转换为 string?我看不到布尔值。

【问题讨论】:

  • In ... w 是否被重新声明为布尔值?如果为 writer 使用更独特的变量名会发生什么?
  • @jon 将“w”更改为“the_writer”。结果相同。

标签: c++ boost boost-spirit boost-bind


【解决方案1】:

占位符

std::cout << val("set name statement to: ") << _3 << "\n"

指的是boost::spirit::_3,它是一个boost.phoenix v2 占位符。中的占位符

boost::bind(&writer::print, &w, ::_3)

是 boost.bind 占位符(自然)。

这些占位符共享相同的行为,甚至引用相同的数据。 _N 形式的 Phoenix 占位符指的是解析器的第 N 个子属性,而绑定占位符具有不同的含义:

  • _1 指的是整个解析器的属性
  • _2 指解析器的上下文
  • _3 指的是bool&amp; 'hit' 参数

在您的情况下,最简单的解决方案是使用boost::phoenix::bind 而不是boost::bind,这样您就可以继续使用_3 来引用解析器的第三个子属性,而不必在@ 中手动选择它987654328@.

或者,仅将语义操作附加到 tok.identifier,以便 boost.bind 的 ::_1 按您的预期工作:

set_name
  = tok.set_
    >> tok.name_
    >> tok.identifier[boost::bind(&writer::print, &w, ::_1)]
;

【讨论】:

  • 这听起来是个好主意。我会尝试并回复您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多