2015-02-23 48 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編譯。因此,請檢查您的增強版本並在必要時進行更新。