2
#include <tuple>
#include <vector>
#include <string>
#include <iostream>
//-------------------------------------------------------------------------
#include <boost/spirit/include/karma.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
//-------------------------------------------------------------------------
namespace ph = boost::phoenix;
namespace karma = boost::spirit::karma;
typedef std::back_insert_iterator<std::string> Sink;
typedef std::tuple<double,int> Data;
typedef std::vector<Data> Container;
struct Generator : karma::grammar<Sink,Container()>
{
  Generator(void) : Generator::base_type(start,"Generator")
  {
    start = data % karma::eol;
    //data = karma::delimit[???];
    return;
  }
  karma::rule<Sink,Container()> start;
  karma::rule<Sink,Data()> data;
};
//-------------------------------------------------------------------------
int main(int argc,char** argv)
{
  Generator generator;
  Container container;
  container.push_back(Data(3.1415,100500));
  container.push_back(Data(2.7183,9000));
  std::string result;
  Sink sink(result);
  bool b = boost::spirit::karma::generate(sink,generator,container);
  std::cerr << (b == true ? result : std::string("Error!")) << std::endl;
  return 0;
}

在规则数据(例如)中,我需要在double之前生成int并使用它进行算术运算。如何在数据规则的语义操作中访问合成属性(元组)的元素?

4

1 回答 1

1

我现在能想到的最快的解决方案就是:

data = delimit [ int_ [ _1 = at_c<1>(_val) ] << double_ [ _1 = at_c<0>(_val) ] ];

因此,完整的示例如下所示:

#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

#include <boost/fusion/adapted.hpp>
#include <boost/tuple/tuple.hpp>
//-------------------------------------------------------------------------
namespace ph = boost::phoenix;
namespace karma = boost::spirit::karma;
typedef std::back_insert_iterator<std::string> Sink;
typedef boost::tuple<double,int> Data;
typedef std::vector<Data> Container;
struct Generator : karma::grammar<Sink,Container()>
{
    Generator(void) : Generator::base_type(start,"Generator")
    {
        using namespace karma;
        using namespace ph;
        data = delimit [ int_ [ _1 = at_c<1>(_val) ] << double_ [ _1 = at_c<0>(_val) ] ];
        start = data % eol;
        return;
    }
    karma::rule<Sink,Container()> start;
    karma::rule<Sink,Data()> data;
};
//-------------------------------------------------------------------------
int main(int argc,char** argv)
{
    Generator generator;
    Container container;
    container.push_back(Data(3.1415,100500));
    container.push_back(Data(2.7183,9000));
    std::string result;
    Sink sink(result);
    bool b = boost::spirit::karma::generate(sink,generator,container);
    std::cerr << (b == true ? result : std::string("Error!")) << std::endl;
    return 0;
}

输出:

100500 3.142
9000 2.718
于 2012-01-13T09:48:26.373 回答