我正在寻找实现可变参数函数的最简单方法,该函数采用 boost::spirit::qi 规则列表并将列表扩展为格式的表达式:rule1 | 规则2 | rule3 |.... 假设规则不合成任何属性。非常感谢您的帮助。
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <string>
#include <iostream>
#include <boost/spirit/include/phoenix_operator.hpp>
namespace qi = boost::spirit::qi;
namespace ph = boost::phoenix;
namespace ascii = boost::spirit::ascii;
using boost::spirit::qi::phrase_parse;
using boost::spirit::qi::ascii::space;
using boost::spirit::iso8859_1::char_;
typedef qi::rule<std::string::const_iterator,ascii::space_type> mrule_t;
typedef qi::rule< std::string::const_iterator,std::string() > wrule_t;
//How to deduce expandBitwise() return type ?
template<typename T>
T expandBitwise(T& t)
{
return t.rule_;
}
template<typename T,typename ...Tail>
T expandBitwise(T& t,Tail& ...tail)
{
return t.rule_ | expandBitwise(tail...);
}
struct TStruct
{
mrule_t rule_;
template<typename T,typename R>
TStruct( T& rVar,const std::string&name, R& rule ) :
rule_( qi::lit( name ) >> rule[ ph::ref( rVar )=qi::_1 ] )
{}
};
template<typename T,typename ...Tail>
void mparse(const std::string& line,T& t,Tail& ...tail)
{
std::string::const_iterator f,l;
f=line.begin();
l=line.end();
// I would like to expand the rules here ...
//if(phrase_parse(f,l,expandBitwise(t,tail...),space ) && f==l)
if( phrase_parse(f, l, t.rule_, space ) && f==l )
std::cout<<"Parsed:"<<line<<std::endl;
else
std::cout<<"Syntax error:"<<line<<std::endl;
}
int main()
{
wrule_t rword=+~space;
std::string par1,par2,par3,par4;
TStruct r1( par1,"-a", rword );
TStruct r2( par2,"-b", rword );
TStruct r3( par3,"-c", rword );
TStruct r4( par4,"-d", rword );
mparse("abc 8.81" ,r1,r2,r3,r4);
mparse("-a atoken" ,r1,r2,r3,r4);
mparse("-b btoken" ,r1,r2,r3,r4);
mparse("-c ctoken" ,r1,r2,r3,r4);
mparse("-d dtoken" ,r1,r2,r3,r4);
return 0;
}