0

I try to save the pointers of Actions class methods in std::map container. When I try to do it compiler shows C3867 and C2440 errors. Here is the screenshot of the errors

#include <iostream>
#include <map>

using namespace std;

typedef void(*FunctionPointer)();

class Actions
{
public:
    Actions(){}
    ~Actions(){}

    void DoSomething() { cout << "Something" << endl; }
};

class Commands
{
public:
    Commands(){}
    ~Commands() {}

    // Initialize commands list
    void Init() { commandsList_["Something"] = actions_.DoSomething; }

    // Calls command using its name
    void CallCommand(std::string commandName) { commandsList_[commandName](); }
private:
    std::map <std::string, FunctionPointer> commandsList_;
    Actions actions_;
};


int main()
{
    Commands commands;
    commands.Init();

    commands.CallCommand("Something");

    return 0;
}

I tried to cast it: commandsList_["Something"] = (FunctionPointer)actions_.DoSomething; but it shows error C2440 Screenshot

I have hundreds of commands and want to reduce complexity of main console method and don't want to call every method one by one. What should I do? Is it even possible to save function as pointer?

bzfbr
  • 93
  • 1
  • 6
  • member functions are not the same as free functions, the pointer types are different – 463035818_is_not_an_ai Jun 30 '16 at 11:38
  • 1
    Don't post screen shots of text. Copy the text instead. And the entire error message too, the error code alone is mostly useless to us humans. – eerorika Jun 30 '16 at 11:48
  • This is what you'd need to do: http://ideone.com/fpRmo4 – Jonathan Mee Jun 30 '16 at 11:57
  • I have answered the duplicate question with a modern answer in hopes that it will be of assistance to you: http://stackoverflow.com/a/38123935/2642059 – Jonathan Mee Jun 30 '16 at 13:14
  • If you're trying to store pointers to member functions you can simply do what Jonathan suggested, but if you're trying to store pointers to different functions/class functions (methods) then one method is to store a void* and then cast it whenever you decide to call the function. http://ideone.com/xxx4EE – Michael Kiros Jun 30 '16 at 13:36

0 Answers0