main.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright Abel Sinkovics (abel@sinkovics.hu) 2011.
  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/foldl1.hpp>
  6. #include <boost/metaparse/build_parser.hpp>
  7. #include <boost/metaparse/transform.hpp>
  8. #include <boost/metaparse/one_of_c.hpp>
  9. #include <boost/metaparse/entire_input.hpp>
  10. #include <boost/metaparse/string.hpp>
  11. #include <boost/metaparse/util/digit_to_int.hpp>
  12. #include <boost/mpl/int.hpp>
  13. #include <boost/mpl/plus.hpp>
  14. #include <boost/mpl/times.hpp>
  15. #include <iostream>
  16. using boost::metaparse::foldl1;
  17. using boost::metaparse::build_parser;
  18. using boost::metaparse::transform;
  19. using boost::metaparse::one_of_c;
  20. using boost::metaparse::entire_input;
  21. using boost::metaparse::util::digit_to_int;
  22. using boost::mpl::int_;
  23. using boost::mpl::plus;
  24. using boost::mpl::times;
  25. /*
  26. * The grammar
  27. *
  28. * expression ::= ('1' | '0')*
  29. */
  30. struct next_element
  31. {
  32. template <class Acc, class B>
  33. struct apply : plus<times<Acc, int_<2> >, B> {};
  34. };
  35. typedef
  36. foldl1<transform<one_of_c<'0', '1'>, digit_to_int<> >, int_<0>, next_element>
  37. S;
  38. typedef build_parser<entire_input<S> > binary_parser;
  39. template <class S>
  40. struct binary : binary_parser::apply<S>::type {};
  41. #ifdef _STR
  42. # error _STR already defined
  43. #endif
  44. #define _STR BOOST_METAPARSE_STRING
  45. #if BOOST_METAPARSE_STD < 2011
  46. int main()
  47. {
  48. using std::cout;
  49. using std::endl;
  50. using boost::metaparse::string;
  51. cout
  52. << binary<string<'1','0','0'> >::value << endl
  53. << binary<string<'1','0','1','1'> >::value << endl
  54. << binary<string<'1'> >::value << endl;
  55. }
  56. #else
  57. int main()
  58. {
  59. using std::cout;
  60. using std::endl;
  61. cout
  62. << binary<_STR("100")>::value << endl
  63. << binary<_STR("1011")>::value << endl
  64. << binary<_STR("1")>::value << endl;
  65. }
  66. #endif