map takes no class function as map_value parameter

Hi there,

I want to process commands in a chat program I've started working on. The way I'm planning to do this is by having every command it's own function.

I wanted to check if the userInput equevalent is to some other string by putting it together in a map.

std::map<std::string, void*> _Functions;

But when I try to insert functions in it it is saying my arguments do not match the argument list.

I have done some research and came to the conclusion that the problem is that the functions I want to use are part of the CommandManager class. Futhermore does the map accept normal voids.

Not acceptable:

_Functions.insert(std::make_pair("/help", &HelpCommand));

void CommandManager::HelpCommand()
{

}

Acceptable:

_Functions.insert(std::make_pair("/help", &help));


void help()
{

}

Can someone help me solve this problem?

Regards,
Geomazzix
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <functional>
#include <map>

struct CommandManager
{
    void HelpCommand() const { std::cout << "CommandManager::HelpCommand()\n" ; }
    int FooCommand( bool arg )
    {
        std::cout << "CommandManager::FooCommand(" << std::boolalpha << arg << ")\n" ;
        return 1 ;
    }
};

int main()
{
    CommandManager cmd_mgr ;

    // http://en.cppreference.com/w/cpp/utility/functional/function
    using command_handler = std::function< void() > ;
    std::map< std::string, command_handler > functions ;

    // http://en.cppreference.com/w/cpp/utility/functional/bind
    functions[ "/help" ] = std::bind( &CommandManager::HelpCommand, std::addressof(cmd_mgr) ) ;
    functions[ "/foo" ] = std::bind( &CommandManager::FooCommand, std::addressof(cmd_mgr), true ) ;

    functions[ "/help" ]() ; // CommandManager::HelpCommand()
    functions[ "/foo" ]() ; // CommandManager::FooCommand(true)

    // typical use
    const auto iter = functions.find( "/help" ) ;
    if( iter != functions.end() ) iter->second() ; // CommandManager::HelpCommand()
    else std::cout << "invalid command\n" ;
}

http://coliru.stacked-crooked.com/a/467a8c35f835f795
http://rextester.com/ODZ97698
Topic archived. No new replies allowed.