使用默认值而不是异常来提升numeric_cast <>?

Rom*_*kov 4 c++ boost

每当boost的numeric_cast<>转换失败时,它都会抛出异常.在boost中是否有类似的模板允许我指定一个默认值,或者在这种情况下我能做的唯一事情就是捕获异常?

我并不太担心所有额外异常处理的性能,但我宁愿使用标准模板而不是编写无用的包装函数.此外,根据过去的经验,我认为提升实际上可能有我想到的,而我根本就没有找到它.

Rob*_*edy 6

numeric_cast函数只boost::numeric::converter使用默认参数调用模板类.其中一个参数是OverflowHandler,默认值是def_overflow_handler,但您可以指定silent_overflow_handler抑制异常.

FloatToIntRounder如果输入参数超出所需范围,则指定将提供所需默认值的参数.该参数通常用于为浮点类型的舍入提供整数,但您可以将其用于任何您想要的任何内容.更多信息,以及描述事件顺序的代码,在converter文档中.

据我所知,Boost没有您想到的东西,但它为您自己构建它提供了便利.


小智 5

template<class Target, class Source>
typename boost::numeric::converter<Target,Source>::result_type
numeric_cast_defaulted(Source arg, Target default_value = Target()) try {
  return boost::numeric_cast<Target>(Source);
}
catch (boost::bad_numeric_cast&) {
  return default_value;
}
Run Code Online (Sandbox Code Playgroud)