[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
CmdLineOptions
From: |
Orlov, Yuriy |
Subject: |
CmdLineOptions |
Date: |
Thu, 6 Mar 2003 15:01:23 -0700 |
Hello guys!
You are doing great job. Common C++ library is very usefull tool for
developers.
I think many programmers around the world spent many time to develop their
own wrapers realization
for system dependent calls, unfortunately including me.
But one comment about your command line option mechanizm. I think it to
complicated for most task that
programmers sovling each day, and may be usefull just for big projects.
Please look to my solution below.
Regards,
Yuri Orlov
#include <map>
#include <vector>
#include <stdio.h>
#define _opt_sign '-'
/* Command line option class */
class clopt
{
public:
clopt() :
name(NULL), value(NULL), format(NULL) {};
clopt(char *_name, void *_value,char *_format = NULL) :
name(_name), value(_value), format(_format) {};
bool operator () (const char* c1, const char* c2) const
{ return (strcmp(c1,c2)<0); };
protected:
char *name;
void *value;
char *format;
friend class cmdline;
};
/* Command line class */
class cmdline
{
public:
cmdline& operator+(clopt &_o) {
olist[_o.name] = &_o;
return *this;
};
void extract(int argc, char* argv[]);
std::vector<char*> param;
private:
std::map<char*,clopt*,clopt> olist;
};
inline void cmdline::extract(int argc, char* argv[])
{
for (int i=0; i<argc; i++) {
if (argv[i][0] == _opt_sign) {
clopt *_o = olist[argv[i]+1];
if (_o)
if (_o->format) {
i++; if (i >= argc) return;
sscanf(argv[i],_o->format,_o->value);
} else *((bool *)_o->value) = true;
} else {
param.push_back(argv[i]);
}
}
}
// --------------------------------------------------------
// Sample usage
// --------------------------------------------------------
#include <iostream>
using namespace std;
main(int argc, char* argv[])
{
int intval = 1; // Default value
bool boolval = false; // Default value
float floatval = -1.0;
cmdline cl;
cl +clopt("intval",&intval,"%d")
+clopt("boolval",&boolval)
+clopt("floatval",&floatval,"%f");
// .............
cl.extract(argc,argv);
cout << "intval=" << intval << endl
<< "boolval=" << boolval << endl
<< "floatval=" << floatval << endl;
return 0;
}
- CmdLineOptions,
Orlov, Yuriy <=