mirror of
https://git.lynn.is/Gwen/argparser.git
synced 2024-05-14 21:31:09 +02:00
55 lines
1.5 KiB
C
55 lines
1.5 KiB
C
|
#ifndef ARGPARSER_SINGLE_ARG_H
|
||
|
#define ARGPARSER_SINGLE_ARG_H
|
||
|
|
||
|
#include <memory>
|
||
|
#include <span>
|
||
|
#include <string>
|
||
|
|
||
|
#include "argument.h"
|
||
|
#include "errors.h"
|
||
|
#include "parse-result.h"
|
||
|
#include "type.h"
|
||
|
|
||
|
namespace argparser {
|
||
|
|
||
|
template<typename T>
|
||
|
class single_arg : public arg, public std::enable_shared_from_this<single_arg<T>> {
|
||
|
public:
|
||
|
single_arg(std::string name, type_handle_impl<T> type) : arg(std::move(name)), type(type) {}
|
||
|
|
||
|
[[nodiscard]] T get(const parse_result &pr) const {
|
||
|
auto v = pr.get_arg(name);
|
||
|
if (!v.has_value()) {
|
||
|
throw errors::missing_argument_error(name);
|
||
|
}
|
||
|
return std::any_cast<T>(v);
|
||
|
}
|
||
|
|
||
|
[[nodiscard]] bool has(const parse_result &pr) const {
|
||
|
return pr.has_arg(name);
|
||
|
}
|
||
|
|
||
|
private:
|
||
|
type_handle_impl<T> type;
|
||
|
|
||
|
void do_parse(std::string input, parse_result &pr) const override {
|
||
|
assert(!pr.get_arg(name).has_value());// a single arg can only be parsed once
|
||
|
auto val = this->parse_single_value(input, type);
|
||
|
pr.set_arg(name, std::make_any<T>(val));
|
||
|
}
|
||
|
|
||
|
bool get_can_parse_more(parse_result &pr) const override {
|
||
|
return !pr.get_arg(name).has_value();
|
||
|
}
|
||
|
|
||
|
bool get_has_parsed_enough(parse_result &pr) const override {
|
||
|
return pr.get_arg(name).has_value();
|
||
|
}
|
||
|
};
|
||
|
|
||
|
template<typename T>
|
||
|
using single_arg_handle = std::shared_ptr<single_arg<T>>;
|
||
|
}// namespace argparser
|
||
|
|
||
|
#endif//ARGPARSER_SINGLE_ARG_H
|