好吧,看来您希望从qi::symbols
解析器转换为karma::symbols
生成器。
我会说这样的事情不存在。而且由于您可能已经寻找过它,我认为可以肯定地假设它没有。
我可以看到它是如何有用的,所以你可以考虑将它贡献给 Spirit Repository。
我在这里花了一些时间编写一个简单的映射器,它可以转换qi::symbols
为karma::symbols
:
template <typename Char, typename T, typename Lookup, typename Filter>
karma::symbols<T, std::basic_string<Char> >
inverse(qi::symbols<Char,T,Lookup,Filter> const& parser)
{
karma::symbols<T, std::basic_string<Char> > generator;
parser.for_each([&generator](std::basic_string<Char> const& symbol, T v)
{
generator.add(v, symbol);
});
return generator;
}
编辑C++03 风格:
template <typename Char, typename T, typename Lookup, typename Filter>
karma::symbols<T, std::basic_string<Char> >
inverse(qi::symbols<Char,T,Lookup,Filter> const& parser)
{
struct _adder {
karma::symbols<T, std::basic_string<Char> > result;
void operator()(std::basic_string<Char> const& symbol, T v) {
result.add(v, symbol);
}
} adder;
parser.for_each(adder);
return adder.result;
}
注意这还不能处理解析符号表中可能重复映射的值。
这是一个简单的示例程序,表明它可以工作: http: //liveworkspace.org/code/3uzQKi
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;
template <typename ItType>
struct parser : public qi::grammar<ItType, int()>
{
parser() : parser::base_type(start)
{
_sym.add("aap", 1)("noot", 2)("mies", 3);
start = _sym;
}
// private:
qi::symbols<char, int> _sym;
qi::rule<ItType, int()> start;
};
template <typename ItType>
struct generator : public karma::grammar<ItType, int()>
{
template<typename Sym>
generator(Sym&& sym) : generator::base_type(start)
{
// _sym.add(1, "aap")(2, "noot")(3, "mies");
_sym = std::move(sym);
start = _sym;
}
private:
karma::symbols<int, std::string> _sym;
karma::rule<ItType, int()> start;
};
template <typename Char, typename T, typename Lookup, typename Filter>
karma::symbols<T, std::basic_string<Char> >
inverse(qi::symbols<Char,T,Lookup,Filter> const& parser)
{
karma::symbols<T, std::basic_string<Char> > generator;
parser.for_each([&generator](std::basic_string<Char> const& symbol, T v)
{
generator.add(v, symbol);
});
return generator;
}
void testcase(std::string const& str)
{
typedef std::string::const_iterator It;
It begin = str.cbegin();
It end = str.cend();
static const parser<It> p;
int out;
bool ok = qi::parse(begin, end, p, out);
std::cout << std::boolalpha << ok << '\n';
std::cout << "remains: '" << std::string(begin, end) << "'\n";
if (ok)
{
std::cout << "parsed value: " << out << "\n";
static const generator<boost::spirit::ostream_iterator> g(inverse(p._sym));
std::cout << "generator: " << karma::format(g, out) << "\n";
}
}
int main()
{
const auto v = std::vector<std::string>{ "aap", "noot", "mies" };
for (auto it=v.begin(); it!=v.end(); ++it)
testcase(*it);
}
输出:
true
remains: ''
parsed value: 1
generator: aap
true
remains: ''
parsed value: 2
generator: noot
true
remains: ''
parsed value: 3
generator: mies