I have a constructor taking an integer.
I also have some data which I'm receiving in the form of uint8_t.
Conceptually this is an integral value with range 0 - 255
However, in c++ it's treated as an unsigned char, and doing things like passing to std::cout will print a char not an integer.
1 2 3 4 5 6 7
|
#include <iostream>
int main()
{
uint8_t val = 56;
std::cout << "val=" << val << std::endl;
return 0;
}
|
output:
In a text-based API, a valid uint8_t value could be received as "134". However, if I say the following:
uint8_t val = boost::lexical_cast<uint8_t>("134");
I get an exception because lexical_cast is attempting to parse it as a char.
The following code will work without overflowing the uint8_t:
uint8_t val = boost::lexical_cast<uint16_t>("134");
Anyway, I had some other code which was failing because I was parsing the uint8_t value incorrectly. I was passing an incorrectly parsed uint8_t value to a constructor. I thought if I put explicit on the constructor I could enforce having to create an int from the uint8_t, and then pass the int to the constructor.
I realise this wouldn't have fixed the incorrect parsing of the uint8_t, but if I was able to prevent implicit conversions, I would have had a compile time error for every instance of passing my (incorrectly parsed) uint8_t value to the ctor.