Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a boost lexical_cast equivalent of C# TryParse?

Intro (from Eric Lippert Blog) :

Vexing exceptions are the result of unfortunate design decisions. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.

The classic example of a vexing exception is Int32.Parse, which throws if you give it a string that cannot be parsed as an integer. But the 99% use case for this method is transforming strings input by the user, which could be any old thing, and therefore it is in no way exceptional for the parse to fail. Worse, there is no way for the caller to determine ahead of time whether their argument is bad without implementing the entire method themselves, in which case they wouldn't need to be calling it in the first place.

Now the important part:

This unfortunate design decision was so vexing that of course the frameworks team implemented TryParse shortly thereafter which does the right thing.

From MSDN Int32.TryParse:

Return Value Type: System.Boolean true if s was converted successfully; otherwise, false.

So colleague recenly was working on some small bit of code that required checking if a string is a number so after thinking about it and realizing there is no good C++ solution(basically it is a for__each/find_if or boost:lexical_cast try catch) I thought how nice it would be to have is_convertible or something from boost?

Ofc i can wrap boost lexical_cast and return true at the end of try block and return false at the end of catch block but I prefer existing practice :) solutions.

like image 895
NoSenseEtAl Avatar asked Nov 28 '12 10:11

NoSenseEtAl


1 Answers

If you can use boost, then you could use boost::conversion::try_lexical_convert:

#include <boost/lexical_cast/try_lexical_convert.hpp>

std::string str("1.2");
double res;
if(boost::conversion::try_lexical_convert<double>(str, res)){
   //everything normal
}
else{
   //we got a problem
}
like image 180
ead Avatar answered Sep 24 '22 11:09

ead