kaycxx-cli
C++ CLI library
Loading...
Searching...
No Matches
parse_value.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Klaus Reimer <k@ailis.de>
2// SPDX-License-Identifier: MIT
3
9#pragma once
10
11#include <charconv>
12#include <concepts>
13#include <exception>
14#include <format>
15#include <string_view>
16#include <system_error>
17#include <type_traits>
18
20
21namespace kaycxx::cli {
22
28template <typename T>
29concept from_chars_parseable = requires(std::string_view text, T& value) {
30 requires std::default_initializable<T>;
31 { std::from_chars(text.data(), text.data() + text.size(), value) } -> std::same_as<std::from_chars_result>;
32};
33
39template <typename T>
41 std::constructible_from<T, std::string_view>;
42
50template <typename T>
51concept from_string_parseable = requires(std::string_view text) {
52 { from_string(text, std::type_identity<T>()) } -> std::same_as<T>;
53};
54
62template <typename T>
64 std::copy_constructible<T> && (
68 );
69
70namespace detail {
71
85template <parseable_value T>
86[[nodiscard]] T parse_value(std::string_view text) {
87 if constexpr (from_chars_parseable<T>) {
88 auto value = T();
89 auto const begin = text.data();
90 auto const end = text.data() + text.size();
91 auto const result = std::from_chars(begin, end, value);
92
93 if (result.ec == std::errc::result_out_of_range) {
94 throw parse_error(std::format("Value \"{}\" is out of range", text));
95 }
96 if (result.ec != std::errc() || result.ptr != end) {
97 throw parse_error(std::format("Invalid value \"{}\"", text));
98 }
99
100 return value;
101 } else {
102 try {
103 if constexpr (from_string_parseable<T>) {
104 return from_string(text, std::type_identity<T>());
105 } else {
106 return T(text);
107 }
108 } catch (parse_error const&) {
109 throw;
110 } catch (std::exception const& error) {
111 throw parse_error(std::format("Invalid value \"{}\" ({})", text, error.what()));
112 } catch (...) {
113 throw parse_error(std::format("Invalid value \"{}\"", text));
114 }
115 }
116}
117
118} // namespace detail
119
120} // namespace kaycxx::cli
Handle for a registered option.
Definition option_handle.hpp:25
Error thrown when command line arguments cannot be parsed.
Definition parse_error.hpp:19
Checks whether a type can be parsed with std::from_chars.
Definition parse_value.hpp:29
Checks whether a type can be parsed with an ADL-discovered from_string function.
Definition parse_value.hpp:51
Checks whether a type can be used as a command line value.
Definition parse_value.hpp:63
Checks whether a type can be constructed from std::string_view.
Definition parse_value.hpp:40
Defines the command line parse error type.
T parse_value(std::string_view text)
Parses a command line value.
Definition parse_value.hpp:86