【发布时间】:2016-08-27 20:07:26
【问题描述】:
Boost Spirit qi::symbols 实现了一个键值对的映射:给一个字符串的一个键,它可以返回一个特定的值。我的问题是:
1) 对于空字符串,是否可以返回默认值? (代码中的 Q1)
2) 对于不是空字符串或键值对映射中列出的键的字符串,是否可以返回一个表明该键无效的值? (代码中的 Q2)
** 以下代码基于 BOOST SPIRIT 文档。 ** 提前感谢您的任何建议。
#include <boost/spirit/include/support_utree.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/assert.hpp>
#include <iostream>
#include <string>
#include <cstdlib>
template <typename P, typename T>
void test_parser_attr(
char const* input, P const& p, T& attr, bool full_match = true)
{
using boost::spirit::qi::parse;
char const* f(input);
char const* l(f + strlen(f));
if (parse(f, l, p, attr) && (!full_match || (f == l)))
std::cout << "ok" << std::endl;
else
std::cout << "fail" << std::endl;
}
int main()
{
using boost::spirit::qi::symbols;
symbols<char, int> sym;
sym.add
("Apple", 1)
("Banana", 2)
("Orange", 3)
;
int i;
test_parser_attr("Banana", sym, i);
std::cout << i << std::endl; // 2
test_parser_attr("", sym, i); // Q1: key is "",
std::cout << i << std::endl; // would like it to be 1 as default
test_parser_attr("XXXX", sym, i); // Q2: key is other than "Apple"/"Banana"/"Orange",
std::cout << i << std::endl; // would like it to be 4
return 0;
}
【问题讨论】:
标签: c++ boost-spirit-qi