For boost::lexical_cast, the character type of the underlying stream is assumed to be char unless either the Source or the Target requires wide-character streaming, in which case the underlying stream uses wchar_t. Following types also can use char16_t or char32_t for wide-character streaming
Boost Lexical Cast
So after doing below changes in your code:
#include <iostream> #include <cstdlib> #include <boost/lexical_cast.hpp> int main() { try { const auto a = boost::lexical_cast<int8_t>("2"); const auto b = boost::lexical_cast<int16_t>("22"); std::cout << a << " and "<< b << std::endl; } catch( std::exception &e ) { std::cout << "e=" << e.what() << std::endl; } return 0; }
Gives below output
2 and 22
So, I feel that each character is taken as char.
So, for const auto a = boost::lexical_cast<int16_t>("2"); 2 is taken as single char which require int8_t.
And, for const auto b = boost::lexical_cast<int16_t>("22"); 22 is taken as two char values which require int16_t.
I hope it helps!
lexical_cast<unsigned char>("127")throwbad_lexical_cast? Answer: Lexical conversion to any char type is simply reading a byte from source. But since the source has more than one byte, the exception is thrown. Please use other integer types such asintorshort int. If bounds checking is important, you can also callboost::numeric_cast: numeric_cast<unsigned char>(lexical_cast<int>("127"));from boost reference. In your caseint8_tis alias forchar.int8_tis an alias tosigned charin all architecture I've seen so far. The problem is that Lexical Cast treats bothsigned charandunsigned charjust likechar, rather than integer types. IMHO, a very unhappy design.