所以我有自己的uint64_t到uint32_t数字演员的政策
struct MyOverflowHandlerPolicy
{
void operator() ( boost::numeric::range_check_result ) {
std::cout << "MyOverflowHandlerPolicy called" << std::endl;
throw boost::numeric::positive_overflow();
};
} ;
如何让它被boost :: numeric_cast使用?
答案 0 :(得分:6)
要使用numeric_cast
,应在每种类型的转化中定义numeric_cast_traits
专精。已使用内置数值类型的默认值定义这些特化。通过定义BOOST_NUMERIC_CONVERSION_RELAX_BUILT_IN_CAST_TRAITS
(details),可以禁用内置类型的特化生成。
这是一个小样本。
#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编译。因此,请检查您的增强版本并在必要时进行更新。