views:

512

answers:

5

Hi

I basically have this problem: right now, we have a system where it gets a string as input, and it basically says ACTION:.

For each of the actions there is an automatically generated function(Rational Rose GRRR), such as

bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
bouncer_comm.askforname().sendAt(msg->sapindex0());

bouncer_comm returns an RTOutSignal, I can't create them manually because of the bizarre structure rose uses.

Right now, my only option is to create a hundred or so if statements, where I do:

if(action == "CHAT")  bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());

Which is realllllyy annoying.

What would be the best way to avoid this? I've looked at / tried countless things, this is a really old version of rational rose (pre 2k) and yeah.

If anyone has any ideas that would be amazing.

+5  A: 

A hash storing function pointers could work well here

cobbal
Could you perhaps care to elaborate? I tried making a map of function pointers but since they take different values it causes problems.
UberJumper
I'd agree if this were C and not C++, but since it's the latter, would have to favor the polymorphic approach
George Jempty
If each method has different signatures, avoiding function pointers is probably in your interest.
Robert P
To be honest, I know very little about boost. Sounds like these other suggestions will work better.
cobbal
+11  A: 

I like @cobbal's idea of the function pointer hash above, but you could replace this conditional logic with polymorphism.

see: http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism

killingmichael
Polymorphism is probably best here, combined with a factory of some sort. Different commands mean a different Command subclass.
strager
Polymorphism is absolutely best, more idiomatically C++
George Jempty
A: 

You could use boost::bind or boost::function and a map. This would allow you to call the correct function, even know each function has a different amount of parameters.

If you don't want any extra code you could use function objects and inheritance.

Brian R. Bondy
+2  A: 

I used polymorphism combined with the factory pattern. I reduced a lot of if's to this :


MyAbstractClass *ac = Factory::getHandlerFor(data);
ac->perform(parameters);
Geo
+1  A: 

I think the easiest is a map of boost::functions.

rlbond