Firstly, do switch to Spirit V2 - which has superseded classical spirit for years now.
Second, you need to make sure an int gets preferred. By default, a double can parse any integer equally well, so you need to use strict_real_policies
instead:
real_parser<double, strict_real_policies<double>> strict_double;
Now you can simply state
number = strict_double | int_;
See
See test program Live on Coliru
#include <boost/spirit/include/qi.hpp>
using namespace boost::spirit::qi;
using A = boost::variant<int, double>;
static real_parser<double, strict_real_policies<double>> const strict_double;
A parse(std::string const& s)
{
typedef std::string::const_iterator It;
It f(begin(s)), l(end(s));
static rule<It, A()> const p = strict_double | int_;
A a;
assert(parse(f,l,p,a));
return a;
}
int main()
{
assert(0 == parse("42").which());
assert(0 == parse("-42").which());
assert(0 == parse("+42").which());
assert(1 == parse("42.").which());
assert(1 == parse("0.").which());
assert(1 == parse(".0").which());
assert(1 == parse("0.0").which());
assert(1 == parse("1e1").which());
assert(1 == parse("1e+1").which());
assert(1 == parse("1e-1").which());
assert(1 == parse("-1e1").which());
assert(1 == parse("-1e+1").which());
assert(1 == parse("-1e-1").which());
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…