options.hpp (1715B)
1 #ifndef GUARD_DRAMATICALLY_MACROPLANKTONIC_SPEED_WALKING_CAVILS_5903 2 #define GUARD_DRAMATICALLY_MACROPLANKTONIC_SPEED_WALKING_CAVILS_5903 3 #pragma once 4 5 #include <functional> 6 #include <span> 7 #include <stdexcept> 8 #include <string_view> 9 10 struct Option 11 { 12 std::string_view key, value_placeholder, help; 13 std::function<void (std::string_view)> apply; 14 }; 15 16 template <typename T> 17 T FromString(std::string_view sv) = delete; 18 19 template<> bool FromString(std::string_view sv); 20 21 #define INT_TYPES(x) \ 22 x(char) x(unsigned char) x(signed char) \ 23 x(short) x(unsigned short) x(int) x(unsigned int) \ 24 x(long) x(unsigned long) x(long long) x(unsigned long long) 25 #define FROM_STRING_SPEC(x) template<> x FromString(std::string_view sv); 26 INT_TYPES(FROM_STRING_SPEC) 27 #undef FROM_STRING_SPEC 28 29 template<> float FromString(std::string_view sv); 30 template<> double FromString(std::string_view sv); 31 32 struct ParseError : std::runtime_error 33 { using std::runtime_error::runtime_error; }; 34 35 struct Exit { int code; }; 36 37 using ParseCallback = void (std::string_view key, std::string_view value); 38 39 namespace Detail 40 { 41 void ParseOneOption( 42 std::string_view sv, const std::function<ParseCallback>& cb); 43 } 44 45 inline void ParseOptions( 46 std::span<std::string_view> args, const std::function<ParseCallback>& cb) 47 { for (std::string_view sv : args) Detail::ParseOneOption(sv, cb); } 48 49 inline void ParseArgs(int argc, char** argv, const std::function<ParseCallback>& cb) 50 { 51 for (int i = 1; i < argc; ++i) 52 Detail::ParseOneOption(argv[i], cb); 53 } 54 55 bool HandleOption( 56 std::span<Option> opts, std::string_view key, std::string_view val); 57 58 void PrintHelp(std::span<const Option> opts); 59 60 // implement this 61 int Main(int argc, char** argv); 62 63 #endif