【发布时间】:2016-08-10 12:26:37
【问题描述】:
我正在尝试使用 qi 创建通用解析器元素,因为很遗憾(必须支持 MSVC)无法使用 X3。 这个想法是有一个模板结构:
template<class T> struct parse_type;
我可以这样使用:
template<class T> T from_string(std::string const& s)
{
T res;
parse_type<T> t;
...
if (phrase_parse(...,parse_type<T>(),...,t))
}
或者像这样专门化
template<class T,class Alloc>
struct parse_type<std::vector<T,Alloc>>
{
// Parse a vector using rule '[' >> parse_type<T> % ',' > ']';
}
主要目的是允许轻松解析例如std::tuple、boost::optional 和 boost::variant(由于 qi 的贪婪特性,最后一个不能是自动的)。
对于如何处理此问题,我将不胜感激。目前我的结构基于 qi::grammar,但 X3 不支持语法,我想在 MSVC 编译它时使用 X3,而且我对必须提供船长也有点不舒服。 另一种方法是在 parse_type 中有一个返回适当规则的静态函数。我正在考虑这是否是一种更清洁的方法?
我们将不胜感激。
Update2:将 code-sn-p 替换为在运行时失败的可编译示例。代码如下:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <string>
#include <string>
#include <iostream>
#include <iostream>
// Support to simplify
using iter = std::string::const_iterator;
void print(std::vector<int> const& v)
{
std::cout << '[';
for (auto i: v) std::cout << i << ',';
std::cout << "]";
}
namespace qi = boost::spirit::qi;
// My rule factory - quite useless if you do not specialise
template<class T> struct ps_rule;
// An example of using the factory
template<class T>
T from_string(std::string const& s)
{
T result;
iter first { std::begin(s) };
auto rule = ps_rule<T>::get();
phrase_parse(first,std::end(s),rule,qi::space,result);
return result;
}
// Specialising rule for int
template<>
struct ps_rule<int>
{
static qi::rule<iter,int()> get() { return qi::int_; }
};
// ... and for std::vector (where the elements must have rules)
template<class T,class Alloc>
struct ps_rule<std::vector<T,Alloc>>
{
static qi::rule<iter,std::vector<T,Alloc>()> get()
{
qi::rule<iter,std::vector<T,Alloc>()> res;
res.name("Vector");
res =
qi::lit('{')
>> ps_rule<T>::get() % ','
>> '}';
return res;
}
};
int main()
{
// This one works like a charm.
std::cout << ((from_string<int>("100") == 100) ? "OK\n":"Failed\n");
std::vector<int> v {1,2,3,4,5,6};
// This one fails
std::cout << ((from_string<std::vector<int>>("{1,2,3,4,5,6}") == v) ? "OK\n":"Failed\n");
}
代码在 boost/function_template.hpp 第 766 行失败:
result_type operator()(BOOST_FUNCTION_PARMS) const
{
if (this->empty())
boost::throw_exception(bad_function_call());
return get_vtable()->invoker
(this->functor BOOST_FUNCTION_COMMA BOOST_FUNCTION_ARGS);
}
这段代码是 boost::function4 中的一个成员函数 ,boost::fusion::vector0 > & ,boost::spirit::unused_type const&> 问题是 get_vtable 返回一个无效的指针。
【问题讨论】:
-
我不是很在乎,但我想知道这里投反对票的原因是什么?
标签: c++ boost-spirit boost-spirit-qi