ChainCLI
A modern C++20 command-line interface library
Loading...
Searching...
No Matches
parser_utils.h
1/*
2 * Copyright 2025 Dominik Czekai
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18#include <iostream>
19#include <sstream>
20#include <string>
21#include <format>
22
23#include "parse_exception.h"
24
25namespace cli::parsing
26{
29{
34 template <typename T> static T parse(const std::string &input)
35 {
36 std::istringstream iss(input);
37 T value;
38
39 if constexpr (std::is_same_v<T, std::string>)
40 {
41 return input; // For strings, just return
42 }
43 else
44 {
45 // Use operator>> for all other types
46 iss >> value;
47 if (iss.fail() || !iss.eof())
48 {
49 throw TypeParseException(std::format("Failed to parse value of type {} from input: {}", typeid(T).name(), input), input, typeid(T));
50 }
51 }
52
53 return value;
54 }
55
60 template <typename T> static void parse(const std::string &input, T &value)
61 {
62 // Call the return-by-value version and assign
63 value = parse<T>(input);
64 }
65};
66} // namespace cli::parsing
Exception thrown when the input string cannot be parsed to the needed type for an argument.
Definition parse_exception.h:62
Helper struct providing static methods for parsing strings into various types.
Definition parser_utils.h:29
static T parse(const std::string &input)
Parses a string input into a value of type T.
Definition parser_utils.h:34
static void parse(const std::string &input, T &value)
Parses a string input into a value of type T.
Definition parser_utils.h:60