main.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright Abel Sinkovics (abel@sinkovics.hu) 2015.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. #include <boost/metaparse/string.hpp>
  6. #include <boost/metaparse/sequence_apply.hpp>
  7. #include <boost/metaparse/last_of.hpp>
  8. #include <boost/metaparse/int_.hpp>
  9. #include <boost/metaparse/token.hpp>
  10. #include <boost/metaparse/lit_c.hpp>
  11. #include <boost/metaparse/entire_input.hpp>
  12. #include <boost/metaparse/build_parser.hpp>
  13. #include <boost/rational.hpp>
  14. #include <boost/config.hpp>
  15. #include <iostream>
  16. using boost::metaparse::sequence_apply2;
  17. using boost::metaparse::last_of;
  18. using boost::metaparse::int_;
  19. using boost::metaparse::token;
  20. using boost::metaparse::lit_c;
  21. using boost::metaparse::entire_input;
  22. using boost::metaparse::build_parser;
  23. template <class Num, class Denom>
  24. struct rational
  25. {
  26. typedef rational type;
  27. static boost::rational<int> run()
  28. {
  29. return boost::rational<int>(Num::type::value, Denom::type::value);
  30. }
  31. };
  32. typedef
  33. sequence_apply2<
  34. rational,
  35. token<int_>,
  36. last_of<lit_c<'/'>, token<int_> >
  37. >
  38. rational_grammar;
  39. typedef build_parser<entire_input<rational_grammar> > rational_parser;
  40. #ifdef RATIONAL
  41. # error RATIONAL already defined
  42. #endif
  43. #define RATIONAL(s) \
  44. (::rational_parser::apply<BOOST_METAPARSE_STRING(s)>::type::run())
  45. #if BOOST_METAPARSE_STD < 2011
  46. int main()
  47. {
  48. std::cout << "Please use a compiler that supports constexpr" << std::endl;
  49. }
  50. #else
  51. int main()
  52. {
  53. const boost::rational<int> r1 = RATIONAL("1/3");
  54. const boost::rational<int> r2 = RATIONAL("4/4");
  55. const boost::rational<int> r3 = RATIONAL("13/11");
  56. std::cout
  57. << r1 << std::endl
  58. << r2 << std::endl
  59. << r3 << std::endl;
  60. }
  61. #endif