为了使用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编译。因此,请检查您的增强版本并在必要时进行更新。