我试图用一个小程序来解析使用Boost.Spirit从/ proc / stat解析cpu使用信息。它主要是工作,但是在使用repeat时我无法编译语法。我错过了什么?
#include <vector>
#include "boost/fusion/include/adapt_struct.hpp"
#define BOOST_SPIRIT_DEBUG
#include "boost/spirit/include/qi.hpp"
#include "boost/iostreams/device/mapped_file.hpp"
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
struct Cpu
{
unsigned int user;
unsigned int nice;
unsigned int system;
unsigned int idle;
unsigned int iowait;
unsigned int irq;
unsigned int softirq;
unsigned int steal;
unsigned int guest;
unsigned int guest_nice;
};
BOOST_FUSION_ADAPT_STRUCT(
Cpu,
(unsigned int, user)
(unsigned int, nice)
(unsigned int, system)
(unsigned int, idle)
(unsigned int, iowait)
(unsigned int, irq)
(unsigned int, softirq)
(unsigned int, steal)
(unsigned int, guest)
(unsigned int, guest_nice)
)
template< typename Iter, typename Skip = ascii::blank_type >
struct Cpu_parser : qi::grammar< Iter, Cpu(), Skip >
{
qi::rule< Iter, Cpu(), Skip > start;
Cpu_parser() : Cpu_parser::base_type(start)
{
using namespace qi;
start = lexeme[lit("cpu") >> omit[-uint_]] >> repeat(10)[uint_];
//start = lexeme[lit("cpu") >> omit[-uint_]] >> uint_ >> uint_ >> uint_ >> uint_ >> uint_ >> uint_ >> uint_ >> uint_ >> uint_ >> uint_;
BOOST_SPIRIT_DEBUG_NODE(start);
}
};
int main(int argc, char** argv)
{
std::vector< Cpu > cpus;
{
std::ifstream ifs("/proc/stat");
ifs >> std::noskipws;
Cpu_parser< boost::spirit::istream_iterator > cpu_parser;
std::cout << phrase_parse(
boost::spirit::istream_iterator(ifs),
boost::spirit::istream_iterator(),
cpu_parser % qi::eol,
ascii::blank,
cpus) << std::endl;
}
return 0;
}
所有单个uint_s的注释行都可以正常工作,但我想知道我在重复时做错了什么。
如果我用无符号整数向量替换Cpu结构,我也可以重复工作。
答案 0 :(得分:4)
你做不到。容易。那是因为repeat()[]
合成了一个容器属性。你的结构是融合序列,而不是容器。
你/可以/伪造它
is_container<Cpu>
。这里有一个示例,用于描述如何在文档中执行操作:http://www.boost.org/doc/libs/1_60_0/libs/spirit/doc/html/spirit/advanced/customize/iterate/container_iterator.html#spirit.advanced.customize.iterate.container_iterator.example。还有一个答案描述了如何使用Live On Coliru。 1}})然而,有好消息:
对于融合序列,std::array
解析器知道该怎么做!
这可以去除80%的脂肪:
<强> this site 强>
qi::auto_
注意
- 输出为
#include "boost/fusion/include/adapt_struct.hpp" #include "boost/spirit/include/qi.hpp" #include <fstream> struct Cpu { unsigned user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice; }; BOOST_FUSION_ADAPT_STRUCT(Cpu, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice) int main() { std::vector<Cpu> cpus; bool ok = [&cpus] { using It = boost::spirit::istream_iterator; using namespace boost::spirit::qi; std::ifstream ifs("/proc/stat"); return parse( It(ifs >> std::noskipws), {}, ("cpu" >> -omit[uint_] >> skip(blank)[auto_]) % eol, cpus); }(); std::cout << std::boolalpha << ok << std::endl; }
。只是不在Coliru上(/ proc / cpu在那里无法访问)。- lambda技巧可以使
true
作用域,同时能够返回using namespace
的值。