Read uint8_t from std::stringstream as a numeric type

You can overload the input operator>> for uint8_t, such as:

std::stringstream& operator>>(std::stringstream& str, uint8_t& num) {
   uint16_t temp;
   str >> temp;
   /* constexpr */ auto max = std::numeric_limits<uint8_t>::max();
   num = std::min(temp, (uint16_t)max);
   if (temp > max) str.setstate(std::ios::failbit);
   return str;
}

Live demo: https://wandbox.org/permlink/cVjLXJk11Gigf5QE

To say the truth I am not sure whether such a solution is problem-free. Someone more experienced might clarify.


UPDATE

Note that this solution is not generally applicable to std::basic_istream (as well as it's instance std::istream), since there is an overloaded operator>> for unsigned char: [istream.extractors]. The behavior will then depend on how uint8_t is implemented.

Tags:

C++