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 6 #include <boost/metaparse/string.hpp> 7 #include <boost/metaparse/sequence_apply.hpp> 8 #include <boost/metaparse/last_of.hpp> 9 #include <boost/metaparse/int_.hpp> 10 #include <boost/metaparse/token.hpp> 11 #include <boost/metaparse/lit_c.hpp> 12 #include <boost/metaparse/entire_input.hpp> 13 #include <boost/metaparse/build_parser.hpp> 14 15 #include <boost/rational.hpp> 16 17 #include <boost/config.hpp> 18 19 #include <iostream> 20 21 using boost::metaparse::sequence_apply2; 22 using boost::metaparse::last_of; 23 using boost::metaparse::int_; 24 using boost::metaparse::token; 25 using boost::metaparse::lit_c; 26 using boost::metaparse::entire_input; 27 using boost::metaparse::build_parser; 28 29 template <class Num, class Denom> 30 struct rational 31 { 32 typedef rational type; 33 runrational34 static boost::rational<int> run() 35 { 36 return boost::rational<int>(Num::type::value, Denom::type::value); 37 } 38 }; 39 40 typedef 41 sequence_apply2< 42 rational, 43 44 token<int_>, 45 last_of<lit_c<'/'>, token<int_> > 46 > 47 rational_grammar; 48 49 typedef build_parser<entire_input<rational_grammar> > rational_parser; 50 51 #ifdef RATIONAL 52 # error RATIONAL already defined 53 #endif 54 #define RATIONAL(s) \ 55 (::rational_parser::apply<BOOST_METAPARSE_STRING(s)>::type::run()) 56 57 #if BOOST_METAPARSE_STD < 2011 58 main()59int main() 60 { 61 std::cout << "Please use a compiler that supports constexpr" << std::endl; 62 } 63 64 #else 65 main()66int main() 67 { 68 const boost::rational<int> r1 = RATIONAL("1/3"); 69 const boost::rational<int> r2 = RATIONAL("4/4"); 70 const boost::rational<int> r3 = RATIONAL("13/11"); 71 72 std::cout 73 << r1 << std::endl 74 << r2 << std::endl 75 << r3 << std::endl; 76 } 77 78 #endif 79 80