Re: how to implement MAP<std::string,TYPE>
Oscar <ro4tub@gmail.com> wrote:
Ben Craig ????????? ?????????????????????????????????
It would be helpful if we knew a little bit more of the context of this
problem. My first guess at what you are trying to do would be a
factory function. If you are looking for a good factory function
abstraction, you may want to look in to Loki's Factory template (
http://loki-lib.sourceforge.net/ ).
the cantext of this problem is:
when the server RECV the client's request ,it runs something ,i use the
COMMAND design
pattern,but how to create the concrete command?
client server
"foo" -> CFooCmd cmd; cmd.run();
"bar" -> CBarCmd cmd; cmd.run();
it looks like server executes something like void run_xxx(); with
command string "xxx",
typedef boost::function<void(void)> function_type;
typedef std::map<std::string,function_type> map_type;
map_type do_command;
now the mapped_type can be a functon or a functor so if your command
classes are not really just created to run and destruct they can be
constructed and placed into do_command, if they are all similiar a
template wrapper can be used. etc
so if the commands have an operator () () this will be excuted below.
do_command["foo"] = CmdFoo();
do_command["bar"] = CmdBar();
...
if server recieves string str then
it merely executes do_command[str]();
function is in boost or tr1, there is a similiar Functor in Loki.
This may be modified to some other function<...> if all the commands
have the same signature [arity, arg typess , return typw]
class Commannder
{
typedef boost::function<void(void)> function_type;
typdef std::map<std::string,function_type> map_type;
map_type do_command();
public:
Commander() {/* initialize map as above */}
void execute(const std::string &cmd); // possibly const char *
{
map_type::iterator it = do_command.find(str);
if(it = do_command.end())
{
// oops invalid command handle it.
}
else
{
// execute it.
it->second();
}
}
};
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]