I created a small function template that checks whether the input lies within the range of the output data type, and throws an exception otherwise. It requires that the input and output data types are integral, and that the size of the input data type is larger than the output data type.
template<typename DestType, typename SrcType>
DestType range_check_and_convert(SrcType const& src)
{
static_assert(sizeof(SrcType) > sizeof(DestType),
"SrcType must be larger than DestType");
static_assert(std::is_integral<SrcType>::value &&
std::is_integral<DestType>::value, "integral types only");
if(src > static_cast<SrcType>(std::numeric_limits<DestType>::max())) {
throw std::out_of_range("input too big");
} else if(src < static_cast<SrcType>(std::numeric_limits<DestType>::min())) {
throw std::out_of_range("input too small");
}
return static_cast<DestType>(src);
}