boost spirit:使用语义动作和凤凰时的参数类型

时间:2011-12-03 10:39:11

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

我使用boost精神来解析数学表达式,并遇到了一个问题,我将其提取到以下代码中。

有一个带有一个标记的简单词法分析器,其属性包含匹配的字符串。解析器定义了一个规则,用于获取令牌的属性并使用它调用函数。函数调用的结果应该是规则的属性值。

这无法编译(calc_something:无法将参数1从const boost :: spirit :: _ 1_type转换为const std :: string&) - 显然是因为qi :: _ 1的类型未正确推断。但是,将操作更改为简单的“cout<< qi :: _ 1”有效。

我是一个相当新的提升精神,但已设法让我的语法行为正确。现在我需要获得解析后的值,我被困在这里并且会感谢我能得到的任何帮助。

// spiritTest.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <tchar.h>

#include <string>
#include <iostream>

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>

namespace qi = boost::spirit::qi;
namespace lex = boost::spirit::lex;
namespace phoenix = boost::phoenix;

template <typename Lexer>
class TestLexer : public lex::lexer<Lexer>
{
public:
    TestLexer()
    {
        number = "(\\d*\\.)?\\d+([eE][-+]?\\d+)?";      
        self = number;
    }

    lex::token_def<std::string> number;
};

int calc_something(const std::string & s)
{
    return 5;
}

template <typename Iterator>
class Parser : public qi::grammar<Iterator, int>
{
public:
    template <typename TokenDef>
    Parser(const TokenDef& tok) : Parser::base_type(value)
    {   
        // the following line causes error C2664: 'calc_something' : cannot convert parameter 1 from 'const boost::spirit::_1_type' to 'const std::string &'    
        value = tok.number [qi::_val = calc_something(qi::_1)];         

        // the following line works as expected
        //value = tok.number [std::cout << qi::_1 << std::endl];            
    }

    qi::rule<Iterator, int> value;
};

int _tmain(int argc, _TCHAR* argv[])
{
    typedef const char* base_iterator_type;
    typedef lex::lexertl::token<base_iterator_type> token_type;
    typedef lex::lexertl::lexer<token_type> lexer_type;
    typedef TestLexer<lexer_type> TestLexer;
    typedef TestLexer::iterator_type iterator_type;
    typedef Parser<iterator_type> Parser;

    TestLexer lexer;
    Parser parser(lexer);

    const char * formula = "530";
    bool result = lex::tokenize_and_parse(formula, formula + strlen(formula), lexer, parser);

    return 0;
}

2 个答案:

答案 0 :(得分:2)

我没有使用spirit lex的经验,但我认为它与qi类似,因此您需要使用phoenix function来执行此操作:

#include <boost/spirit/include/phoenix_function.hpp>

struct calc_something_impl
{
  template <typename T1>
  struct result { typedef int type; };

  int operator()(const std::string & s) const
  {
    return 5;
  }
};

boost::phoenix::function<calc_something_impl> calc_something;

答案 1 :(得分:1)

埃迪已经发现了部分问题;我设法让另外两个变化:

  • 语法和规则的签名必须使用合成属性的函数调用语法,即<Iterator, int()>
  • 虽然我无法得到懒惰的凤凰功能eddi详细工作(它编译,但从未被调用),切换到凤凰V3使其工作。在您的第一个精神包括之前添加:

#define BOOST_SPIRIT_USE_PHOENIX_V3 1