定义一个符号,它可能是提升精神中文字函数的一部分

时间:2015-02-06 16:49:39

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

我正在尝试阅读一个数学函数,该函数依赖于带有boost :: spirit的符号t

在下面的示例中,我正在尝试评估"tan(t)"中的函数t=1.2。 而不是

Exit: 1, value = 2.5721 

我得到了

Exit: 1, value = 1.2 

我理解当我尝试阅读"tan(t)"函数时,不会计算t的正切,而是将t的值分配给单词{{ 1}}。是否可以在不更改符号tan的情况下绕过此行为?而且,解析不应该失败吗?

t

1 个答案:

答案 0 :(得分:1)

您必须重新排序规则。您的符号(t)正在吃tan的第一个字母。所以,你实际上根本没有解析所有输入!

如果启用调试,您将看到此输出:

<expression>
<try>tan(t)</try>
<success>an(t)</success>
<attributes>[1.2]</attributes>
</expression>
Exit: 1, value = 1.2

皇家之路&#34;解决这个问题的方法是使用Spirit Repository中的Qi Distinct Keyword指令:boost::spirit::qi keywords and identifiers

<强> Live On Coliru

#define BOOST_SPIRIT_DEBUG
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi_symbols.hpp>
#include <boost/spirit/repository/include/qi_distinct.hpp>
#include <boost/phoenix/stl/cmath.hpp>

namespace qi = boost::spirit::qi;
namespace ascii=boost::spirit::ascii;
using boost::spirit::ascii::space;
using boost::spirit::qi::symbols;


template< typename Iterator >
struct Grammar : public qi::grammar<  Iterator, double(), ascii::space_type >
{

    Grammar() : Grammar::base_type(expression)
    {
        using qi::double_;
        using qi::_val;
        using qi::_1;
        using boost::spirit::repository::qi::distinct;

        expression = double_
                   | distinct(qi::char_("a-zAZ09_")) [ symbol ]
                   | function
                   | group;

        function =  "tan"  >> group [_val = boost::phoenix::tan(_1)];
        group = '(' >> expression >> ')' ;

        BOOST_SPIRIT_DEBUG_NODES((expression)(function)(group));
  }

    qi::rule<Iterator, double(), ascii::space_type> expression, function, group;
    qi::symbols<char, double > symbol;
};


int main()
{
    typedef std::string::iterator iterator;
    Grammar<iterator> grammar;
    std::string function = "tan(t)";
    grammar.symbol.add("t",1.2);
    double value;
    bool r = qi::phrase_parse(function.begin(), function.end(), grammar, space, value);
    std::cout << "Exit: " << r << ", value = " << value << std::endl;

    return 0;
}

带有调试信息的输出是:

<expression>
  <try>tan(t)</try>
  <function>
    <try>tan(t)</try>
    <group>
      <try>(t)</try>
      <expression>
        <try>t)</try>
        <success>)</success>
        <attributes>[1.2]</attributes>
      </expression>
      <success></success>
      <attributes>[1.2]</attributes>
    </group>
    <success></success>
    <attributes>[2.57215]</attributes>
  </function>
  <success></success>
  <attributes>[2.57215]</attributes>
</expression>
Exit: 1, value = 2.57215