通过boost :: lexical_cast捕获溢出

时间:2018-10-11 14:12:04

标签: c++ boost

我想捕获 boost :: lexicat_cast 溢出的方式与捕获 boost :: numeric_cast 溢出的方式相同。有可能吗?

下面的第一个 try 块抛出 boost :: numeric :: negative_overflow

第二个块不会引发异常(这不是 lexical_cast 错误吗?)

尽管在以下示例中使用了 unsigned int ,但我正在寻找一种适用于任何整数类型的方法。

#include <boost/numeric/conversion/cast.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
    unsigned int i;

    try
    {
        int d =-23;
        i = boost::numeric_cast<unsigned int>(d);
    }
    catch (const boost::numeric::bad_numeric_cast& e)
    {
        std::cout << e.what() << std::endl;
    }

    std::cout << i << std::endl; // 4294967273

    try
    {
        char c[] = "-23";
        i = boost::lexical_cast<unsigned int>(c);
    }
    catch (const boost::bad_lexical_cast& e)
    {
        std::cout << e.what() << std::endl;
    }

    std::cout << i << std::endl; // 4294967273

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您可以使用少量的Spirit写下您想要的内容:

Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <iostream>

template <typename Out, typename In> Out numeric_lexical_cast(In const& range) {

    Out value;

    {
        using namespace boost::spirit::qi;
        using std::begin;
        using std::end;

        if (!parse(begin(range), end(range), auto_ >> eoi, value)) {
            struct bad_numeric_lexical_cast : std::domain_error {
                bad_numeric_lexical_cast() : std::domain_error("bad_numeric_lexical_cast") {}
            };
            throw bad_numeric_lexical_cast();
        }
    }

    return value;
}

int main()
{
    for (std::string const& input : { "23", "-23" }) try {
        std::cout << " == input: " << input << " -> ";
        auto i = numeric_lexical_cast<unsigned int>(input);
        std::cout << i << std::endl;
    } catch (std::exception const& e) {
        std::cout << e.what() << std::endl;
    }
}

打印

 == input: 23 -> 23
 == input: -23 -> bad_numeric_lexical_cast