If you don't have access to boost::numeric_cast
, you can write a simple imitation:
template <typename T, typename S>
T range_check(const S &s) {
assert(s <= std::numeric_limits<T>::max());
assert(s >= std::numeric_limits<T>::min());
return static_cast<T>(s); // explicit conversion, no warnings.
}
return range_check<int>(strtol(some_value,0,8));
Actually that's a bit of a cheat, since it doesn't work for floating point destination types. min()
isn't the same bound for them as it is for integer types, you need to check against +/- max()
. Exercise for the reader.
Whether you use assert or some other error-handling depends what you actually want to do about invalid input.
There's also boost::lexical_cast
(off-hand I don't know how to make that read octal) and stringstream. Read the type you want, not the type that happens to have a C library function for it.