2015-02-23 50 views
5

所以,我有我自己的uint64_t中政策uint32_t的数字投如何使用numeric_cast策略?

struct MyOverflowHandlerPolicy 
{ 
    void operator() (boost::numeric::range_check_result) { 
     std::cout << "MyOverflowHandlerPolicy called" << std::endl; 
     throw boost::numeric::positive_overflow(); 
    }; 
} ; 

我如何得到它通过的boost :: numeric_cast使用吗?

回答

6

为了使用numeric_cast,numeric_cast_traits专业化应该定义每种类型的转换。这些专业化已经使用默认值为内置数字类型定义。通过定义BOOST_NUMERIC_CONVERSION_RELAX_BUILT_IN_CAST_TRAITSdetails),可以禁用内置类型的专业化生成。

这是一个小样本。

#include <iostream> 
#include <stdexcept> 

#define BOOST_NUMERIC_CONVERSION_RELAX_BUILT_IN_CAST_TRAITS 
#include <boost/numeric/conversion/cast.hpp> 

using namespace std; 

struct YourOverflowHandlerPolicy 
{ 
    void operator() (boost::numeric::range_check_result r) { 
     cout << "YourOverflowHandlerPolicy called" << endl; 
     if (r != boost::numeric::cInRange) { 
      throw logic_error("Not in range!"); 
     } 
    }; 
}; 

namespace boost { namespace numeric { 
template <> 
struct numeric_cast_traits<uint32_t, uint64_t> 
{ 
    typedef YourOverflowHandlerPolicy overflow_policy; 
    typedef UseInternalRangeChecker range_checking_policy; 
    typedef Trunc<uint64_t>   rounding_policy; 
}; 

template <> 
struct numeric_cast_traits<uint64_t, uint32_t> 
{ 
    typedef YourOverflowHandlerPolicy overflow_policy; 
    typedef UseInternalRangeChecker range_checking_policy; 
    typedef Trunc<uint32_t>   rounding_policy; 
}; 
}} //namespace boost::numeric; 

int main() 
{ 
    try { 
     cout << boost::numeric_cast<uint32_t>((uint64_t)1) << endl; // OK 
     cout << boost::numeric_cast<uint32_t>((uint64_t)1<<31) << endl; // OK 
     cout << boost::numeric_cast<uint32_t>((uint64_t)1<<32) << endl; // Exception 
    } catch (...) { 
     cout << "exception" << endl; 
    } 

    return 0; 
} 

输出:

YourOverflowHandlerPolicy called 
1 
YourOverflowHandlerPolicy called 
2147483648 
YourOverflowHandlerPolicy called 
exception 

注:我有升压发布1.55.0,我不知道该把它编制的最低版本级别,但它不与1.46.0编译。因此,请检查您的增强版本并在必要时进行更新。