是否有C#TryParse的boost lexical_cast等效项? [英] Is there a boost lexical_cast equivalent of C# TryParse?

查看:97
本文介绍了是否有C#TryParse的boost lexical_cast等效项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介(来自Eric Lippert博客) :

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.

令人烦恼的异常的经典示例是Int32.Parse,它抛出 如果给它一个不能解析为整数的字符串.但是 该方法有99%的用例是通过 用户,这可能是任何旧事物,因此绝不是 异常使解析失败.更糟糕的是,没有办法 呼叫者提前确定他们的论点是否不好 无需自己执行整个方法,在这种情况下, 不需要首先调用它.

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.

现在重要的部分:

这个不幸的设计决定是如此令人烦恼,以至于 框架团队此后不久实施了TryParse, 正确的事情.

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

从MSDN Int32.TryParse:

From MSDN Int32.TryParse:

返回值类型:System.Boolean如果s被转换,则为true 成功地;否则为假.

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

因此,同事最近只在处理一小段代码,需要检查字符串是否为数字,因此在考虑它并意识到没有好的C ++解决方案之后(基本上是for__each/find_if或boost:lexical_cast try catch )我以为拥有is_convertible或来自boost的东西会有多好?

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我可以包装boost lexical_cast并在try块的末尾返回true,在catch块的末尾返回false,但是我更喜欢现有的实践:)解决方案.

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.

推荐答案

如果可以使用boost,那么可以使用

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
}

这篇关于是否有C#TryParse的boost lexical_cast等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆