Để sử dụng chuyên môn numeric_cast
, numeric_cast_traits
nên được xác định trên từng loại chuyển đổi. Các chuyên ngành này đã được xác định với các giá trị mặc định cho các kiểu số có sẵn. Có thể vô hiệu hoá việc tạo chuyên môn cho các kiểu dựng sẵn bằng cách xác định BOOST_NUMERIC_CONVERSION_RELAX_BUILT_IN_CAST_TRAITS
(details).
Đây là mẫu chạy nhỏ.
#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;
}
Output:
YourOverflowHandlerPolicy called
1
YourOverflowHandlerPolicy called
2147483648
YourOverflowHandlerPolicy called
exception
Lưu ý: Tôi có thúc đẩy phát hành 1.55.0, tôi không biết mức phát hành tối thiểu để có được nó được biên dịch, nhưng nó không được biên dịch với 1.46.0. Vì vậy, hãy kiểm tra bản phát hành và cập nhật tăng cường của bạn nếu cần.