templates - c++ - other way of implementing function calls in switch cases -


i've got code below:

void cashflow::execute (int cmd) {     switch(cmd):     {         case buy:             buyproc ();             break;         case sell:             sellproc ();             break;          ......     } } 

what i'm thinking of doing maybe create map std::map <int, void (cashflow::*)()> cashflowprocs;

then maybe use mcashflowprocs = boost::assign::map_list_of (buy, &cashflow::buyproc)(...etc)(..etc.);

then can call (this->(mcashflowprocs [cmd]))();

how turn template can reused? there issues implementation?

note not using c++11

could there issues implementation?

yes, hard maintain, adding/removing command need lot of maintenance, error prone, , difficult test. suggest design change before trying improve particular code.

1 - if can change design:

use class represent command

class command {     public:         virtual void execute() = 0;         virtual ~command() {};; };  class buycommand : public command {     public:         virtual void execute() { cout << "buy"; } };  class sellcommand : public command {     public:         virtual void execute() { cout << "sell"; } };  // ... command* bc = new buycommand(); // ... bc->execute(); 

2 - if (unfortunately) cant change design way

if cmd enumeration known @ compile time, , has limited size, can use array of boost::function, , should regroup command in enum instead of using int.

enum { buy = 0; sell = 1; nb_cmds= 2 }; ... boost::array<nb_cmds, boost::function<void()>>  // n number of commands. 

indexing array with, cmd, call function has index cmd in array.

if don't know @ compile time how many commands/functions need, might need replace array std::vector.

if 1 day can use c++11, replace boost:: std:: in above snippets.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -