diff --git a/Modules/Core/include/mitkLexicalCast.h b/Modules/Core/include/mitkLexicalCast.h new file mode 100644 index 0000000000..65829242a5 --- /dev/null +++ b/Modules/Core/include/mitkLexicalCast.h @@ -0,0 +1,75 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef mitkLexicalCast_h +#define mitkLexicalCast_h + +#include + +namespace mitk +{ + template + inline Target lexical_cast(const std::string &arg) + { + Target result = Target(); + + // Let Boost try to do the lexical cast, which will most probably succeed! + if (!boost::conversion::detail::try_lexical_convert(arg, result)) + { + // Fallback to our own conversion using std::istringstream. This happens with + // Apple LLVM version 9.1.0 (clang-902.0.39.1) on darwin17.5.0 and very small + // floating point numbers like 0.2225e-307. + std::istringstream stream(arg); + stream.exceptions(std::ios::badbit); + + try + { + stream.unsetf(std::ios::skipws); + stream.precision(boost::detail::lcast_get_precision()); + stream >> result; + } + catch (const std::ios_base::failure &) + { + boost::conversion::detail::throw_bad_cast(); + } + } + + return result; + } +} + +namespace boost +{ + template <> + inline float lexical_cast(const std::string &arg) + { + return mitk::lexical_cast(arg); + } + + template <> + inline double lexical_cast(const std::string &arg) + { + return mitk::lexical_cast(arg); + } + + template <> + inline long double lexical_cast(const std::string &arg) + { + return mitk::lexical_cast(arg); + } +} + +#endif