我想用boost :: spirit :: karma在引號中轉義字符串。這工作正常,如果它只是一個字符串。但是,對於std :: vector中boost :: variant類型的字符串,它不會。只是打印字符串確實有效,但我不明白爲什麼。boost :: spirit :: karma輸出字符串的引號
行(1)工作正常,但沒有做我想做的。第(2)行應該這樣做,但不是。
#include <iostream>
#include <string>
#include <boost/variant.hpp>
#include <boost/spirit/include/karma.hpp>
namespace karma = boost::spirit::karma;
typedef std::vector<boost::variant<int, std::string>> ParameterList;
typedef boost::variant<int, std::string, ParameterList> Parameter;
main()
{
using karma::int_;
using boost::spirit::ascii::string;
using karma::eol;
using karma::lit;
std::string generated;
std::back_insert_iterator<std::string> sink(generated);
// (1)
karma::rule<std::back_insert_iterator<std::string>, ParameterList()> parameterListRule = (int_ | string) % lit(", "); // This works!
// (2)
//karma::rule<std::back_insert_iterator<std::string>, ParameterList()> parameterListRule = (int_ | (lit('"') << string << lit('"'))) % lit(", "); // This does not work
karma::rule<std::back_insert_iterator<std::string>, Parameter()> parameterRule = (int_ | (lit('"') << string << lit('"')) | parameterListRule) << eol; // This does work, even though it also escapes the string in a pair of quotation marks
karma::generate(sink, parameterRule, 1); // Works
karma::generate(sink, parameterRule, "foo"); // Works
karma::generate(sink, parameterRule, Parameter(ParameterList{1, "foo"})); // Only works using rule (1), not with (2)
std::cout << generated;
}
這解決了它到底。關於爲什麼第(1)行和第(2)行不行的任何解釋? – Xoph
對不起沒有。從組合本身就可以期待它,但似乎業力在轉發這裏的屬性時有一些問題,雖然'karma :: lit'不公開任何。但我不是這裏的專家,也許@sehe更多地瞭解這一點。但你學會迅速解決這些怪癖;-) –