#include <boost/cast.hpp>
polymorphic_cast polymorphic_downcast
<boost/lexical_cast.hpp>
lexical_cast bad_lexical_cast
int main(int argc, char * argv[]) { using boost::lexical_cast; using boost::bad_lexical_cast; std::vector<short> args; while(*++argv) { try { args.push_back(lexical_cast<short>(*argv)); } catch(bad_lexical_cast &) { args.push_back(0); } } ... }
For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior oflexical_cast
, the conventionalstd::stringstream
approach is recommended. Where the conversions are numeric to numeric,boost::numeric_cast
may offer more reasonable behavior thanlexical_cast
.