0

So I am programming a small bot that will do different actions, like moving, interacting, grabbing, and more in a game. I made all of these actions to be functions of the same format (bool Move(int direction), bool Interact(int type), ...) and I wanted to put them into an array so that the bot only has to check through them once every time it wants to do something.

I've tried solutions I found on the internet (for void functions) like using a typedef, or this:

    bool Move(int type);
    bool Interact(int type);

    bool (*baseAction[2])(int type) = { Move, Interact };

but it doesn't seem to work, it says that a value of type "bool (Character::)(int type)" cannot be used to initialize an entity of type "bool ()(int type)"

If someone understands how to make these, I would be extra grateful if you could also tell me how to do this on dynamic arrays like std::vector or std::list

  • Please show a [mre] – Alan Birtles Jun 28 '23 at 09:52
  • 2
    If these functions are non-static members in some class, you should mention that in your question. – n. m. could be an AI Jun 28 '23 at 09:55
  • An alternative to storing member functions can be making those functions `static` – static functions you *can* assign to ordinary function pointers, though you then need an explicit replacement for the implicit `this` parameter of member functions, i.e. you'd add `Character& instance` as an additional parameter. – Aconcagua Jun 28 '23 at 09:57
  • Is an array of pointer-to-member-functions really more desirable than a member function that calls the functions? Either situation requires multiple touches and neither seems totally ideal. But at least a member function call seems to make more sense. At least, given what little information there is here. – sweenish Jun 28 '23 at 11:02

1 Answers1

1

Use pointer to member.

class Character {
   public:
    bool Move(int type);
    bool Interact(int type);
};
bool (Character::*baseAction[2])(int type) = {&Character::Move,
                                              &Character::Interact};

int main() {
    Character character;
    for (int type = 0; type < 2; type++) {
        (character.*baseAction[type])(type);
    }
    return 0;
}
  • Indeed – obviously they are unkown to question author, though, and she/he might yet need be hinted to differing call syntax (`(c.*f)(12)`/`(c->*f)(10)` with parentheses being necessary due to function call having higher precedence). – Aconcagua Jun 28 '23 at 09:55