2

I try to create an array of pointers of member function of my current class but without success for the moment...

I already tried many things, here is my code:

// Human.hpp

#include <iostream>

class Human
{
    private:
        void meleeAttack(std::string const & target);
        void rangedAttack(std::string const & target);
        void intimidatingShout(std::string const & target);
    public:
        void action(std::string const & action_name, std::string const & target);
};
// Human.cpp

#include "Human.hpp"

// ...

void    Human::action(std::string const & action_name, std::string const & target)
{
    std::string actionsStr[] = {"meleeAttack", "rangedAttack", "intimidatingShout"};

    typedef void (Human::*Actions)(std::string const & target);
    Actions actions[3] = {&Human::meleeAttack, &Human::rangedAttack, &Human::intimidatingShout};

    for (int i = 2; i >= 0; i--)
        if (actionsStr[i] == action_name)
        {
            actions[i](target); // there is an error HERE
            break;
        }
}

This code generate an error on compilation:

main.cpp:41:23: error: called object type 'Actions' (aka 'void (Human::*)(const std::string &)') is not a function or function pointer
            actions[i](target);
            ~~~~~~~~~~^
1 error generated.

What is the good way to do it ?

mch
  • 9,424
  • 2
  • 28
  • 42
Victor Castro
  • 1,232
  • 21
  • 40
  • 1
    A pointer to a non-member function and a pointer to a member function is not the same. Pointers to member functions needs an *object* to be called on (what becomes the `this` pointer). You might want to read about [`std::function`](http://en.cppreference.com/w/cpp/utility/functional/function) and [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/bind). – Some programmer dude Apr 04 '17 at 11:29
  • 1
    You probably want to read about [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map) as well. – Some programmer dude Apr 04 '17 at 11:31
  • Possible duplicate of [C++ Call Pointer To Member Function](http://stackoverflow.com/questions/14814158/c-call-pointer-to-member-function) – AndyG Apr 04 '17 at 11:48

1 Answers1

7
for (int i = 2; i >= 0; i--)
    if (actionsStr[i] == action_name)
    {
        (this->*(actions[i]))(target);
        break;
    }
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142