Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- integer %=
- attr_cast<int,std::string>(
- lexeme[
- -(char_('+') | char_('-')) >>
- char_("1-9") >> *char_("0-9")
- ]
- )
- ;
- template <>
- struct transform_attribute<int, std::string, qi::domain>
- {
- // input type
- typedef std::string& type;
- static std::string pre(int & d) {
- return "";
- }
- static void post(int & val, const type attr) {
- val = boost::lexical_cast<int>(attr);
- }
- static void fail(int &) {}
- };
- integer %= qi::int_; // Job Done
- bool ok = parse(f, l,
- (matches['-'] | -lit('+') >> attr(false)) [ phx::ref(negative) = _1 ] >> // sign
- eps [ _val = 0 ] >>
- +digit [ _val *= 10, _val += (_1 - '0') ],
- parsed);
- namespace boost { namespace spirit { namespace traits {
- template <typename Int>
- struct assign_to_attribute_from_value<
- Int,
- std::string,
- typename std::enable_if<std::is_integral<Int>::value, void>::type // Enabler
- >
- {
- static void call(std::string const& val, Int& attr) {
- //std::cout << __PRETTY_FUNCTION__ << "('" << val << "')n";
- attr = boost::lexical_cast<Int>(val);
- }
- };
- } } }
- // boost lexical_cast does not usefully support `char` types as integrals... (SIC)
- template <>
- struct assign_to_attribute_from_value<signed char, std::string> {
- static void call(std::string const& val, signed char& attr) {
- int tmp;
- assign_to_attribute_from_value<int, std::string>::call(val, tmp);
- attr = static_cast<signed char>(tmp);
- }
- };
- template <>
- struct assign_to_attribute_from_value<unsigned char, std::string> {
- static void call(std::string const& val, unsigned char& attr) {
- unsigned int tmp;
- assign_to_attribute_from_value<unsigned int, std::string>::call(val, tmp);
- attr = static_cast<unsigned char>(tmp);
- }
- };
- Int parsed = 0;
- bool ok = parse(f, l, as_string [ -char_("-+") >> +digit ], parsed);
- Int parsed = 0;
- bool ok = qi::parse(f, l, qi::auto_, parsed);
- #include <boost/spirit/include/qi.hpp>
- template <typename Int>
- void do_test() {
- for (Int const testcase : { std::numeric_limits<Int>::min(), Int(), std::numeric_limits<Int>::max() }) {
- auto const input = std::to_string(testcase);
- auto f(input.begin()), l(input.end());
- Int parsed = 0;
- bool ok = boost::spirit::qi::parse(f, l, boost::spirit::qi::auto_, parsed);
- if (!ok || f!=l)
- throw std::runtime_error("parse error");
- std::cout << std::boolalpha << (testcase==parsed) << "t" << testcase << " -> " << parsed << "n";
- }
- }
- int main() {
- do_test<int16_t>(); do_test<uint16_t>();
- do_test<int32_t>(); do_test<uint32_t>();
- do_test<int64_t>(); do_test<uint64_t>();
- do_test<intmax_t>(); do_test<uintmax_t>();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement