我使用 boost spirit 来解析数学表达式并遇到了我提取到以下代码中的问题。
有一个带有一个标记的简单词法分析器,具有保存匹配字符串的属性。解析器定义了一个规则,该规则旨在获取令牌的属性并使用它调用函数。函数调用的结果应该是规则的属性值。
这无法编译(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;
}