From e250da5003bcc7a7068e54b11ba86e51563255be Mon Sep 17 00:00:00 2001 From: Martin Braun Date: Mon, 26 Aug 2019 10:51:52 -0700 Subject: utils: cast: Add from_str() typecast This is the inverse to std::to_string(), and we can overload it with UHD-internal types. --- host/lib/utils/CMakeLists.txt | 1 + host/lib/utils/cast.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 host/lib/utils/cast.cpp (limited to 'host/lib') diff --git a/host/lib/utils/CMakeLists.txt b/host/lib/utils/CMakeLists.txt index b4dd72c94..74b292fbb 100644 --- a/host/lib/utils/CMakeLists.txt +++ b/host/lib/utils/CMakeLists.txt @@ -219,6 +219,7 @@ set_source_files_properties( # Append sources ######################################################################## LIBUHD_APPEND_SOURCES( + ${CMAKE_CURRENT_SOURCE_DIR}/cast.cpp ${CMAKE_CURRENT_SOURCE_DIR}/csv.cpp ${CMAKE_CURRENT_SOURCE_DIR}/config_parser.cpp ${CMAKE_CURRENT_SOURCE_DIR}/compat_check.cpp diff --git a/host/lib/utils/cast.cpp b/host/lib/utils/cast.cpp new file mode 100644 index 000000000..635d844ee --- /dev/null +++ b/host/lib/utils/cast.cpp @@ -0,0 +1,39 @@ +// +// Copyright 2019 Ettus Research, a National Instruments Brand +// +// SPDX-License-Identifier: GPL-3.0-or-later +// + +#include + +using namespace uhd; + +template <> +double cast::from_str(const std::string& val) +{ + try { + return std::stod(val); + } catch (std::invalid_argument&) { + throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to double!"); + } catch (std::out_of_range&) { + throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to double!"); + } +} + +template <> +int cast::from_str(const std::string& val) +{ + try { + return std::stoi(val); + } catch (std::invalid_argument&) { + throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to int!"); + } catch (std::out_of_range&) { + throw uhd::runtime_error(std::string("Cannot convert `") + val + "' to int!"); + } +} + +template <> +std::string cast::from_str(const std::string& val) +{ + return val; +} -- cgit v1.2.3