7 Şubat 2018 Çarşamba

spirit karma grammar struct

Kullanım
Şöyle yaparız.
std::cout << boost::spirit::karma::format(MyGrammar(), foo) << std::endl;
Constructor
Şöyle yaparız. İlk başlangıç kuralını belirtir.
template<typename Iterator>
struct MyKarmaGrammar : ka::grammar<Iterator, MyStruct()> {
  MyKarmaGrammar() : MyKarmaGrammar::base_type(request_) {
  
    //REQUEST
    request_ %= lit('{') [ _f = true ]
            <<  str_prop_("one"s) <<
                int_prop_("two"s) <<
                dbl_prop_("three"s)
            << '}';
    }

private:
  bool _is_first_field = true;
  //GENERAL RULES
  ka::rule<Iterator, void(std::string)> key_;
  ka::rule<Iterator, boost::optional<double>(std::string)> dbl_prop_;
  ka::rule<Iterator, boost::optional<int>(std::string)> int_prop_;
  ka::rule<Iterator, boost::optional<std::string>(std::string)> str_prop_;
  ka::rule<Iterator> delim;

  //REQUEST
  ka::rule<Iterator, MyStruct()> request_;
};
Örnek
Elimizde şöyle bir kod olsun.
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/spirit/include/karma.hpp>
#include <iomanip>
namespace bsk = boost::spirit::karma;
namespace bpt = boost::posix_time;

template <typename It = boost::spirit::ostream_iterator>
struct TimeDurationGenerator : bsk::grammar<It, bpt::time_duration()>
{
  TimeDurationGenerator() : TimeDurationGenerator::base_type(start_) {
    duration_ = bsk::stream;
    start_    = duration_;
  }
private:
  struct wrap {
    bpt::time_duration d;
    wrap(bpt::time_duration const& d) : d(d) {}
    friend std::ostream& operator<<(std::ostream& os, wrap const& w) {
      return os << std::setfill('0') << std::internal
                << std::setw(3) << std::showpos   << w.d.hours() << ":"
                << std::setw(2) << std::noshowpos << std::abs(w.d.minutes());
    }
  };
  bsk::rule<It, bpt::time_duration()> start_;
  bsk::rule<It, wrap()> duration_;
};
Şöyle yaparız.
for (auto str : { "-7:30", "7", "323:87:13" }) {
  std::cout << format(TimeDurationGenerator<>{}, bpt::duration_from_string(str)) << "\n";
}
Çıktı olarak şunu alırız.
-07:30
+07:00
+324:27
Örnek
Elimizde şöyle bir kod olsun.
struct MyIntsGen:
  bsk::grammar<boost::spirit::ostream_iterator, std::tuple<int, int, int>()>
{
  MyIntsGen() : MyIntsGen::base_type(start_)
  {

    start_ = '<' 
            << bsk::int_
            << ','
            << bsk::int_
            << ','
            << bsk::int_
            << '>';
  }

  ~MyIntsGen() = default;
  bsk::rule<boost::spirit::ostream_iterator, std::tuple<int, int, int>()> start_;
};
Şöyle yaparız.
std::tuple<int, int, int> ms = { 300, 20, 1 };
std::cout << boost::spirit::karma::format(MyIntsGen(), ms) << std::endl;
Çıktı olarak şunu alırız.
<300,20,1>

Hiç yorum yok:

Yorum Gönder