Medical Imaging Interaction Toolkit  2026.06.00
Medical Imaging Interaction Toolkit
mitkLexicalCast.h
Go to the documentation of this file.
1 /*============================================================================
2 
3 The Medical Imaging Interaction Toolkit (MITK)
4 
5 Copyright (c) German Cancer Research Center (DKFZ)
6 All rights reserved.
7 
8 Use of this source code is governed by a 3-clause BSD license that can be
9 found in the LICENSE file.
10 
11 ============================================================================*/
12 
26 #ifndef mitkLexicalCast_h
27 #define mitkLexicalCast_h
28 
29 #include <boost/lexical_cast.hpp>
30 
31 namespace mitk
32 {
45  template <typename Target>
46  inline Target lexical_cast(const std::string &arg)
47  {
48  Target result = Target();
49 
50  // Let Boost try to do the lexical cast, which will most probably succeed!
51  if (!boost::conversion::detail::try_lexical_convert(arg, result))
52  {
53  // Fallback to our own conversion using std::istringstream. This happens with
54  // Apple LLVM version 9.1.0 (clang-902.0.39.1) on darwin17.5.0 and very small
55  // floating point numbers like 0.2225e-307.
56  std::istringstream stream(arg);
57  stream.exceptions(std::ios::badbit);
58 
59  try
60  {
61  stream.unsetf(std::ios::skipws);
62  stream.precision(boost::detail::lcast_precision<Target>::value);
63  stream >> result;
64  }
65  catch (const std::ios_base::failure &)
66  {
67  boost::conversion::detail::throw_bad_cast<std::string, Target>();
68  }
69  }
70 
71  return result;
72  }
73 }
74 
75 namespace boost
76 {
82  template <>
83  inline float lexical_cast<float, std::string>(const std::string &arg)
84  {
85  return mitk::lexical_cast<float>(arg);
86  }
87 
93  template <>
94  inline double lexical_cast<double, std::string>(const std::string &arg)
95  {
96  return mitk::lexical_cast<double>(arg);
97  }
98 
104  template <>
105  inline long double lexical_cast<long double, std::string>(const std::string &arg)
106  {
107  return mitk::lexical_cast<long double>(arg);
108  }
109 }
110 
111 #endif
Find image slices visible on a given plane.
Target lexical_cast(const std::string &arg)
Convert a string to a numeric target type with an std::istringstream fallback.