DryChem 1.0.0
A generic, compile-time C++ toolbox with no dependencies for the modern computational chemistry project.
Loading...
Searching...
No Matches
lexicalCast.hpp
Go to the documentation of this file.
1// Copyright (c) 2020-2025 Cody R. Drisko. All rights reserved.
2// Licensed under the MIT License. See the LICENSE file in the project root for more information.
3//
4// Name: lexicalCast.hpp
5// Author: crdrisko
6// Date: 11/05/2020-07:34:56
7// Description: A common function for converting between strings and other (input streamable) types
8
9#ifndef DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_STRINGS_UTILS_LEXICALCAST_HPP
10#define DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_STRINGS_UTILS_LEXICALCAST_HPP
11
12#include <sstream>
13#include <string>
14#include <type_traits>
15#include <utility>
16
19
20namespace CppUtils::Strings
21{
33 template<typename T, typename CharTraits = std::char_traits<char>>
34 inline auto lexical_cast(const std::basic_string<char, CharTraits>& str)
35 {
36 if constexpr (std::is_same_v<T, std::basic_string<char, CharTraits>>)
37 return str;
38 else
39 {
40 try
41 {
42 T var;
43 std::basic_istringstream<char, CharTraits> stream;
44
45 stream.str(str);
46 stream.exceptions(std::ios::failbit | std::ios_base::badbit);
47
48 stream >> var;
49
50 return var;
51 }
52 catch (const std::ios_base::failure&)
53 {
55 Errors::ErrorMessage {"Common-Utilities", "Error in lexical_cast, default value returned."});
56
57 return T {};
58 }
59 }
60 }
61
65 template<typename TO, typename FROM, typename = std::enable_if_t<std::is_pointer_v<std::decay_t<FROM>>>>
66 inline auto lexical_cast(FROM&& str)
67 {
68 return lexical_cast<TO, std::char_traits<char>>(std::forward<FROM>(str));
69 }
70} // namespace CppUtils::Strings
71
80#define DEFINE_LEXI_CAST_OVERLOAD(TYPE, ABBREVIATION) \
81 template<> \
82 inline auto ::CppUtils::Strings::lexical_cast<TYPE, std::char_traits<char>>(const std::string& str) \
83 { \
84 return std::sto##ABBREVIATION(str); \
85 }
86
87DEFINE_LEXI_CAST_OVERLOAD(long double, ld)
92DEFINE_LEXI_CAST_OVERLOAD(unsigned long, ul)
93DEFINE_LEXI_CAST_OVERLOAD(long long, ll)
94DEFINE_LEXI_CAST_OVERLOAD(unsigned long long, ull)
95
96
97#undef DEFINE_LEXI_CAST_OVERLOAD
98
99#endif
#define DEFINE_LEXI_CAST_OVERLOAD(TYPE, ABBREVIATION)
Definition lexicalCast.hpp:80
void printErrorMessage(const ErrorMessage &error)
Definition errorHandling.hpp:30
Definition ciString.hpp:17
auto lexical_cast(const std::basic_string< char, CharTraits > &str)
Definition lexicalCast.hpp:34
Definition errorTypes.hpp:32