Boost Spirit qi :: symbols implementiert eine Karte von Schlüssel-Wert-Paaren: Geben Sie einen Schlüssel einer Zeichenkette ein, sie kann einen bestimmten Wert zurückgeben. Meine Fragen sind:Boost Spirit Qi Symbole Standardwert und Nullwert
1) Ist es für eine leere Zeichenkette möglich, einen Standardwert zurückzugeben? (Q1 im Code)
2) Ist es für eine Zeichenfolge, die nicht eine leere Zeichenfolge oder die Schlüssel in der Zuordnung der Schlüssel/Wert-Paare ist, möglich, einen Wert zurückzugeben, der angibt, dass der Schlüssel ungültig ist? (Q2 im Code)
** Der folgende Code basiert auf dem BOOST SPIRIT-Dokument. ** Vielen Dank im Voraus für Anregungen.
#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;
}
+1. Ich habe zu 80% genau das geschrieben. – sehe
Super! Perfekte Lösung, detaillierte Erklärung, schnelle Antwort. Vielen Dank. – jianz