在boost::spirit
,我怎样才能读入一个,立即在数据库中string
查找它的值并将值分配给一个?因此,即使它被解析为字符串,规则的属性也会是。int
boost::spirit
int
int
例如,这个输入
myCoolKey 3.4
可以解析为一对:(87, 3.4),其中字符串“myCoolKey”通过(伯克利)数据库查找(int,double)
映射到。87
我想要这样的代码:
typedef std::pair<int, double> Entry;
qi::rule<Iterator, Entry(), Skipper> entry;
entry %= +qi::char_[qi::_val = mylookup(qi::_1)]
>> qi::double_;
这是一个完整的代码示例。我将如何调用查找已解析字符串的函数,并将boost::spirit
查找到的值分配给int
?
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/fusion/include/std_pair.hpp>
namespace qi = boost::spirit::qi;
typedef std::pair<int, double> Entry;
struct Lookup {
MyDB db;
int lookup(std::string const& str) {
return db.lookup(str);
}
};
template <typename Iterator, typename Skipper>
struct MyGrammar : qi::grammar<Iterator, std::vector<Entry>(), Skipper> {
MyGrammar() : MyGrammar::base_type(entries) {
entry %= +qi::char_[qi::_val = myLookup.lookup(qi::_1)]
>> qi::double_;
entries = +entry;
}
Lookup myLookup;
qi::rule<Iterator, Entry(), Skipper> entry;
qi::rule<Iterator, std::vector<Entry>(), Skipper> entries;
};
int main() {
typedef boost::spirit::istream_iterator It;
std::cin.unsetf(std::ios::skipws);
It it(std::cin), end;
MyGrammar<It, qi::space_type> entry_grammar;
std::vector<Entry> entries;
if (qi::phrase_parse(it, end, entry_grammar, qi::space, entries)
&& it == end) {
BOOST_FOREACH(Entry const& entry, entries) {
std::cout << entry.first << " and " << entry.second << std::endl;
}
}
else {
std::cerr << "FAIL" << std::endl;
exit(1);
}
return 0;
}