【发布时间】:2012-01-18 10:04:16
【问题描述】:
我尝试了解Boost.Spirit 的工作原理。不幸的是,文档对我来说太简洁了,我无法弄清楚它是如何工作的。
那么,让我们来解决我的问题。我尝试为std::complex 类型编写解析器,它的工作方式与内置解析器相同,例如int_ 或 double_。我希望它解析不同形式的复数,例如1.2+2i、3-i*4、5*i 等。老实说,我卡住了,不知道该怎么办。我试过这种方法:
typedef std::complex<double> Complex;
struct complex_parser : qi::grammar<Iterator, Complex(), ascii::space_type>
{
complex_parser() : complex_parser::base_type(value)
{
real = (
double_[_val = _1]
);
imaginary = (
( double_[_val = Complex(0.0, _1)] >> -(lit('*')) >> 'i' )
| ( 'i' >> -(lit('*')) >> double_[_val = Complex(0.0, _1)] )
);
value = (
imaginary[_val = _1]
| real[_val = _1] >> -('+' >> imaginary[_val += _1])
| real[_val = _1] >> -('-' >> imaginary[_val -= _1])
);
}
qi::rule<Iterator, Complex(), ascii::space_type> value;
qi::rule<Iterator, double(), ascii::space_type> real;
qi::rule<Iterator, double(), ascii::space_type> imaginary;
};
但它不起作用。甚至不编译,因为当imaginary被解析时,占位符_1不是double类型:
错误 C2665: 'std::complex::complex' : 6 个重载都不能转换所有参数类型 [...] 在尝试匹配参数列表时 '(double, const boost::spirit:: _1_type)'
但是为什么呢?我给出了imaginary 规则(以及real)double() 参数,而不是Complex()。它不应该使占位符成为double-equivalent 类型吗?如果不是,那为什么还要在规则中设置类型?以及如何正确使用它们?
【问题讨论】:
标签: c++ boost-spirit