我需要将字符串解析为布尔值;特别是
ack
我希望解析器使用true
设置布尔变量; noack
我希望解析器使用false
设置布尔变量; 请注意,我不想使用函数qi::parse
的返回值;我希望qi::parse
函数设置一个作为参数给出的布尔变量。类似于以下(不编译)代码:
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
using namespace boost::spirit;
int main() {
bool b;
std::string s("ack");
auto it = s.begin();
if (qi::parse(it, s.end(), < need a rule here... >, b))
std::cout << "Value: " << std::boolalpha << b << std::endl;
return 0;
}
提前多多感谢。
答案 0 :(得分:0)
我想到的最简单的方法是"noack" >> qi::attr(false)
及其补充。添加eoi
以确保解析完整输入:
<强> Live On Coliru 强>
#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
namespace qi = boost::spirit::qi;
int main() {
for (std::string const s : {"ack","noack","oops","ack 2",""}) {
bool b;
if (qi::parse(s.begin(), s.end(), ("ack" >> qi::attr(true) | "noack" >> qi::attr(false)) >> qi::eoi, b))
std::cout << "'" << s << "' -> " << std::boolalpha << b << std::endl;
else
std::cout << "'" << s << "' -> FAIL\n";
}
}
打印
'ack' -> true
'noack' -> false
'oops' -> FAIL
'ack 2' -> FAIL
'' -> FAIL
使用symbol
更优雅:
<强> Live On Coliru 强>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
namespace qi = boost::spirit::qi;
struct acknoack_type : qi::symbols<char, bool> {
acknoack_type() { this->add("ack", true)("noack", false); }
} static const acknoack;
int main() {
for (std::string const s : {"ack","noack","oops","ack 2",""}) {
bool b;
if (qi::parse(s.begin(), s.end(), acknoack >> qi::eoi, b))
std::cout << "'" << s << "' -> " << std::boolalpha << b << std::endl;
else
std::cout << "'" << s << "' -> FAIL\n";
}
}