所以我有自己的uint64_t到uint32_t数字转换的政策
struct MyOverflowHandlerPolicy
{
void operator() ( boost::numeric::range_check_result ) {
std::cout << "MyOverflowHandlerPolicy called" << std::endl;
throw boost::numeric::positive_overflow();
};
} ;
Run Code Online (Sandbox Code Playgroud)
如何让它被boost :: numeric_cast使用?
为了使用numeric_cast,numeric_cast_traits应在每种类型转换上定义专门化.已使用内置数值类型的默认值定义这些特化.可以通过定义BOOST_NUMERIC_CONVERSION_RELAX_BUILT_IN_CAST_TRAITS(细节)来禁用内置类型的特化生成.
这是一个小样本.
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
YourOverflowHandlerPolicy called
1
YourOverflowHandlerPolicy called
2147483648
YourOverflowHandlerPolicy called
exception
Run Code Online (Sandbox Code Playgroud)
注意:我有1.55.0的升级版本,我不知道编译它的最低版本级别,但它不是用1.46.0编译的.因此,请检查您的增强版本并在必要时进行更新.
| 归档时间: |
|
| 查看次数: |
685 次 |
| 最近记录: |