Boost lexical_cast throws bad_lexical_cast when converting types

Using boost to convert one type to another.

#include <boost/lexical_cast.hpp>
int8_t num = 0;
std::string integerString = boost::lexical_cast<std::string>(num);

Will this even work?

thumbs-down-smiley
No, because int8_t is a char in this case. So it will die in a horrible fire, ie. you will get a bad_lexical_cast exception.

glibmm-ERROR **:
unhandled exception (type std::exception) in signal handler:
what: bad lexical cast: source type value could not be interpreted as target

You must static cast to an integer type first:

boost::lexical_cast<std::string>(static_cast<int>(num));

Posted by admica   @   20 April 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional