c++ - Parsing command line arguments and use them to initialize application that has to be implemented using abstract factory pattern -


i have written application parses command line , initializes application, in c language. required application written in c++. following code snippet extracts/parses arguments , calls respective functions.

void (* const optionfuncptr[])(char *pstr) = {                                 (seta),(getb), (setc), (setd), (erase), (foptions), (goperations),                                 (showhelp), (setinput), (undefined), (undefined), (setlbit), (undefined), (undefined),                                 (outputdata), (programoptions), (readall), (readdata), (soptions), (testmode),                                 (undefined), (verifydata), (woptions), (fillunspecific), (readlbits), (noprogessindicator)                                 };  int main(int argc, char *argv[]) {  ...// code for( int = 1; < argc; i++ )     {         param = argv[i];          /* allow parameters start '-' */         if( param[0] != '-' )             throw new errormsg( "all parameters must start '-'!" );          if( strlen( param ) <= 1 )             throw new errormsg( "parameters cannot minus without characters!" );          value = param[1] - 'a';         if(value > 26)             throw new errormsg("you have not entered valid command line parameter");          (*optionfuncptr[value])(&param[2]);         }  //some more code return 0; } 

as can seen, code in c. , need write in c++. noob c++. have read lot of articles, have not been able concrete thing yet. don't know how implement using c++.

the methods calling may different class. think achievable using functors. not sure. helpful if 1 can give small example, carry things forward. need use abstract factory pattern also.

your code valid c++. should. if need make more c++, create abstract argument handler base class

struct arghandler {    virtual ~arghandler();    virtual void operator(const std::string& arg) = 0; }; 

derive showhelp etc ,

arghandler& getarghandler(int i) {   static std::map<int, std::shared_ptr<arghandler>> handlers = {std::make_pair(0, std::make_shared<showhelp>(), ...};    // add error handling here if not found.   return *(handlers.find(i)->second); } 

of course, move free function , static factory class. can create hierarchy of factories , turn whole thing abstract factory pattern, honestly, see no point in that.


Comments