USRP Hardware Driver and USRP Manual  Version: 4.6.0.0-7-gece7c4811
UHD and USRP Manual
cast.hpp
Go to the documentation of this file.
1 //
2 // Copyright 2014-2015 Ettus Research LLC
3 // Copyright 2018 Ettus Research, a National Instruments Company
4 // Copyright 2019 Ettus Research, a National Instruments Brand
5 //
6 // SPDX-License-Identifier: GPL-3.0-or-later
7 //
8 
9 #pragma once
10 
11 #include <uhd/config.hpp>
12 #include <uhd/exception.hpp>
13 #include <iomanip>
14 #include <sstream>
15 #include <string>
16 
17 namespace uhd { namespace cast {
19 //
20 // Example:
21 // uint16_t x = hexstr_cast<uint16_t>("0xDEADBEEF");
22 // Uses stringstream.
23 template <typename T>
24 inline T hexstr_cast(const std::string& in)
25 {
26  T x;
27  std::stringstream ss;
28  ss << std::hex << in;
29  ss >> x;
30  return x;
31 }
32 
35 //
36 // Example:
37 // 10, 0x10, 010 get parsed to decimal 10, 16, 8.
38 // uint32_t x = fromstr_cast<uint32_t>("0xaffe");
39 // Uses istringstream.
40 template <typename T>
41 inline T fromstr_cast(const std::string& in)
42 {
43  T x;
44  std::istringstream is(in);
45  is >> std::setbase(0) >> x;
46  return x;
47 }
48 
50 template <typename data_t>
51 data_t from_str(const std::string&)
52 {
53  throw uhd::runtime_error("Cannot convert from string!");
54 }
55 
56 // Specializations of `uhd::cast::from_str()` for supported data types
57 
59 //
60 // Examples evaluating to `true`: 'True', 'Yes', 'y', '1', empty string
61 // Examples evaluating to `false`: 'false', 'NO', 'n', '0'
62 // Throws `uhd::runtime_error` if the string can't be converted to `bool`
63 template <>
64 UHD_API bool from_str(const std::string& val);
65 
67 template <>
68 UHD_API double from_str(const std::string& val);
69 
71 template <>
72 UHD_API int from_str(const std::string& val);
73 
75 //
76 // This function simply returns the incoming string
77 template <>
78 UHD_API std::string from_str(const std::string& val);
79 
80 }} // namespace uhd::cast
Definition: exception.hpp:131
T fromstr_cast(const std::string &in)
Definition: cast.hpp:41
T hexstr_cast(const std::string &in)
Convert a hexadecimal string into a value.
Definition: cast.hpp:24
Definition: build_info.hpp:12
#define UHD_API
Definition: config.h:87
data_t from_str(const std::string &)
Generic cast-from-string function.
Definition: cast.hpp:51