Skip to content

Instantly share code, notes, and snippets.

@milasudril
Created May 21, 2022 08:36
Show Gist options
  • Save milasudril/461ec3c3ea68c23a5c185d7fd9162f14 to your computer and use it in GitHub Desktop.
Save milasudril/461ec3c3ea68c23a5c185d7fd9162f14 to your computer and use it in GitHub Desktop.
Simple dd style command line parser
#include <map>
#include <string>
#include <algorithm>
/**
* Accepts a `dd` style (foo=bar) command line. For simplicity it has
* no support parameter descriptions.
*/
class command_line
{
public:
using storage_type = std::map<std::string, std::string, std::less<>>;
using key_type = storage_type::key_type;
using value_type = storage_type::value_type;
using mapped_type = storage_type::mapped_type;
explicit command_line(int argc, char** argv)
{
for(int k = 1; k < argc; ++k)
{
auto const arg = std::string_view{argv[k]};
auto const i = std::ranges::find(arg, '=');
if(i == std::end(arg))
{ throw std::runtime_error{std::string{arg}.append(" is missing a value")}; }
m_storage[std::string{std::begin(arg), i}] = std::string{i + 1, std::end(arg)};
}
}
auto const& operator[](std::string_view key) const
{
auto i = m_storage.find(key);
if(i == std::end(m_storage))
{ throw std::runtime_error{std::string{"Mandatory arguemnt "}.append(key).append(" not given")}; }
return i->second;
}
auto begin() const { return std::begin(m_storage); }
auto end() const { return std::end(m_storage); }
auto size() const { return std::size(m_storage); }
private:
storage_type m_storage;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment