Quote:Original post by NIm
I was actually using it to represent the ai for the creature. I hypothesize that it will become faster to use a pointer than a switch when I get about 20 different behaviors. I tdefinitely needs to be profiled both ways though.
That's fine, but polymorphism can be used to accomplish the same thing without extra overhead and with much nicer syntax. In your case, what you'd probably do is create a polymorphic class to represent the func() process - say we have an abstract base class "CreatureBehaviour", which we then derive from. Each Creature holds a pointer to CreatureBehaviour, and delegates to it. If there is only one function that CreatureBehaviour really needs to provide (aside from construction and destruction), in C++ we can use the operator() for that instead of a named member function, in order to clean up the syntax a bit:
class CreatureBehaviour { // whatever else is necessary public: virtual CreatureBehaviour* operator() (Creature& owner) = 0; // We return a pointer to some CreatureBehaviour object so as to represent // a change in behaviour that results from the execution - if the behaviour // should stay the same, we can just "return this;".}class Creature { CreatureBehaviour * action; public: void act() { action = action(*this); }}
This is the Strategy pattern, specifically the Run and Return Successor variant which I have personally found most useful in the past. In C++, the main difficulty is in managing the objects - you probably should use smart pointers instead of the raw ones that are illustrated (this is something that is much easier in a GC environment).