gpt4 book ai didi

c++ - token 解析器语义操作

转载 作者:行者123 更新时间:2023-11-30 03:08:00 25 4
gpt4 key购买 nike

我已经根据 spirit lex example 4 中显示的代码编写了一个可用的 token 解析器

我的规则之一是这样的

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

这很好用。当出现

SET NAME xyz

如我所料输出

set name statement to: 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) : error C2664: 'R boost::_mfi::cmf1::operator ()(const U &,A1) const' : cannot convert parameter 2 from 'bool' to 'const std::basic_string '1>        with1>        [1>            R=void,1>            T=eCrew::rule::writer,1>            A1=const std::string &,1>            U=eCrew::rule::writer *1>        ]1>        and1>        [1>            _Elem=char,1>            _Traits=std::char_traits,1>            _Ax=std::allocator1>        ]1>        Reason: cannot convert from 'bool' to 'const std::string'1>        No constructor could take the source type, or constructor overload resolution was ambiguous

为什么编译器提示尝试从 bool 转换为 string?我看不到 bool 值。

最佳答案

占位符在

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 个子属性,而绑定(bind)占位符具有不同的含义:

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

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

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

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

关于c++ - token 解析器语义操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5478546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com