我如何实现const在Boost精神? [英] How can i implement const in Boost Spirit?

查看:164
本文介绍了我如何实现const在Boost精神?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Boost Spirit现在感兴趣,并试图建立一些东西。我们可以使用Spirit在C ++中实现类似于const的东西吗?例如,用户将定义一个项目:

I am interested in Boost Spirit nowadays and trying to build something. Can we implement something like a const in C++ using Spirit? For instance, user will define an item like;

constant var PROG_LANG="Java"; 

constant var似乎很奇怪,我接受,但你有想法。

"constant var" seems weird, I accept but you got the idea. I searched the internet but can't found anything about it.

推荐答案

BigBoss说的是什么:)

What the BigBoss said :)

只有我没有语义动作 - 使它远远少于... verbose(参见提升精神:语义动作是邪恶的):

Only I'd do without the semantic actions - making it far less... verbose (See also Boost Spirit: "Semantic actions are evil"?):

vdef = 
    ("constant" >> attr(true) | attr(false)) >>
    "var" >> identifier >> '=' >> identifier_value >> ';' ;

这使用 qi :: attr 来计算默认值(缺少常量关键字)。

That's all. This uses qi::attr to account for the default (missing constant keyword).

这是一个完整的演示输出:

Here's a full demo with output:

http://liveworkspace.org/code/c9e4bef100d2249eb4d4b88205f85c4b

输出:

parse success: 'var myvariable = "has some value";'
data: false;myvariable;has some value;
parse success: 'constant var myvariable = "has some value";'
data: true;myvariable;has some value;

代码:

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>

namespace qi    = boost::spirit::qi;
namespace karma = boost::spirit::karma;
namespace phx   = boost::phoenix;

struct var_definition {
    bool is_constant;
    std::string name;
    std::string value;

    var_definition() : is_constant( false ) {}
};

BOOST_FUSION_ADAPT_STRUCT(var_definition, (bool, is_constant)(std::string, name)(std::string, value))


void doParse(const std::string& input)
{
    typedef std::string::const_iterator It;

    qi::rule<It, std::string()> identifier, identifier_value;
    qi::rule<It, var_definition(), qi::space_type> vdef;

    {
        using namespace qi;

        identifier_value = '"' >> lexeme [ +~char_('"') ] > '"';
        identifier       = lexeme [ +graph ];
        vdef             = 
            ("constant" >> attr(true) | attr(false)) >>
            "var" >> identifier >> '=' >> identifier_value >> ';' ;
    }

    var_definition data;

    It f(std::begin(input)), l(std::end(input));
    bool ok = qi::phrase_parse(f,l,vdef,qi::space,data);
    if (ok)   
    {
        std::cout << "parse success: '" << input << "'\n";
        std::cout << "data: " << karma::format_delimited(karma::auto_, ';', data) << "\n";
    }
}

int main()
{
    doParse("var myvariable = \"has some value\";");
    doParse("constant var myvariable = \"has some value\";");
}

这篇关于我如何实现const在Boost精神?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆