MRPT  2.0.1
from_string.h
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 
10 #pragma once
11 
12 #include <sstream>
13 #include <string>
14 
15 namespace mrpt
16 {
17 namespace internal
18 {
19 inline std::istringstream& get_istringstream()
20 {
21  static thread_local std::istringstream stream;
22  stream.str("");
23  return stream;
24 }
25 } // namespace internal
26 
27 /** Converts from string to any data type that supports reading (>>) from a text
28  * stream. In case of error, the given default value is returned, or an
29  * exception raised. \ingroup mrpt_core_grp
30  */
31 template <typename T>
32 inline T from_string(
33  const std::string& s, const T& defValue = T{}, bool throw_on_error = true)
34 {
35  auto& iss(internal::get_istringstream());
36  iss.str(s);
37  T result = defValue;
38  if (!(iss >> result))
39  {
40  if (throw_on_error)
41  throw std::runtime_error(
42  std::string("[from_string()] Cannot parse string: ") + s);
43  }
44  return result;
45 }
46 
47 } // namespace mrpt
T from_string(const std::string &s, const T &defValue=T{}, bool throw_on_error=true)
Converts from string to any data type that supports reading (>>) from a text stream.
Definition: from_string.h:32
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
std::istringstream & get_istringstream()
Definition: from_string.h:19



Page generated by Doxygen 1.8.14 for MRPT 2.0.1 Git: 0fef1a6d7 Fri Apr 3 23:00:21 2020 +0200 at vie abr 3 23:20:28 CEST 2020