Skip to content

Instantly share code, notes, and snippets.

@quaat
Created July 5, 2013 12:16
Show Gist options
  • Save quaat/5934155 to your computer and use it in GitHub Desktop.
Save quaat/5934155 to your computer and use it in GitHub Desktop.
An argument parser for use with Qt. The parser itself stores the keywords as properties in QCoreApplication.
#ifndef ARG_PARSER_H_DEF
#define ARG_PARSER_H_DEF
#include <QCoreApplication>
#include <QString>
#include <QStringList>
// some unique keyword.
char static const *restkeyword = "unique-9c6e6236e14a43";
class ArgParser;
class Opt
{
char const *key;
QString const defaultValue;
Opt();
public:
Opt( char const * k, QString const & d)
: key(k)
, defaultValue (d)
{}
friend class ArgParser;
};
class Rest
{};
class ArgParser{
public:
ArgParser()
: args(QCoreApplication::arguments())
{}
ArgParser& operator << (Opt const &option)
{
qApp->setProperty(option.key, QVariant(parseArg(option.key, option.defaultValue)));
return *this;
}
ArgParser& operator << (Rest)
{
qApp->setProperty(restkeyword, QVariant(args));
return *this;
}
static QString option ( QString const & keyword ) {
return QCoreApplication::instance()->property(qPrintable(keyword)).toString();
}
static QStringList rest () {
return QCoreApplication::instance()->property(restkeyword).toStringList();
}
private:
QString nextArg( QString const & arg )
{
Q_ASSERT(args.contains(arg));
int const idx = args.indexOf(arg);
args.removeAt(idx);
if( args.size() <= idx) {
qWarning() << "Missing arguments to options" << arg;
return QString();
}
return args.takeAt(idx);
}
QString parseArg( QString const &key, QString const &defaultValue )
{
return (args.contains(key) ?
nextArg(key) :
defaultValue );
}
private:
QStringList args;
};
#endif // ARG_PARSER_H_DEF
@quaat
Copy link
Author

quaat commented Jul 5, 2013

Usage:
ArgParser parser;
parser << Opt("--foo", "defaultFoo") << Opt("--bar", "defaultBar" << Rest()

Retrieve values like this:
ArgParser::option("--foo") // => "defaultFoo" or some user defined option
ArgParser::option("--bar") // => "defaultBar" or some user defined option
ArgParser::res() // => "A list of strings with additional arguments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment