64,644
社区成员
发帖
与我相关
我的任务
分享
try
{
string strTmpVar = "-11";
unsigned long aaa = boost::lexical_cast<unsigned long>(strTmpVar);
}
catch(boost::bad_lexical_cast& e) {
// bad lexical cast: source type value could not be interpreted as target
std::cout << e.what() << std::endl;
int aa = -1;
}
catch(std::bad_cast&e)
{
int aa = 1;
}
int main()
{
using boost::numeric_cast;
using boost::numeric::bad_numeric_cast;
using boost::numeric::positive_overflow;
using boost::numeric::negative_overflow;
try
{
int i=42;
short s=numeric_cast<short>(i); // This conversion succeeds (is in range)
}
catch(negative_overflow& e) {
std::cout << e.what();
}
catch(positive_overflow& e) {
std::cout << e.what();
}
try
{
float f=-42.1234;
// This will cause a boost::numeric::negative_overflow exception to be thrown
unsigned int i=numeric_cast<unsigned int>(f);
}
catch(bad_numeric_cast& e) {
std::cout << e.what();
}
double d= f + numeric_cast<double>(123); // int -> double
unsigned long l=std::numeric_limits<unsigned long>::max();
try
{
// This will cause a boost::numeric::positive_overflow exception to be thrown
// NOTE: *operations* on unsigned integral types cannot cause overflow
// but *conversions* to a signed type ARE range checked by numeric_cast.
unsigned char c=numeric_cast<unsigned char>(l);
}
catch(positive_overflow& e) {
std::cout << e.what();
}
return 0;
}
string strTmpVar = "-11a";