Avinash
Avinash

Reputation: 13257

C++ Function pointer map with Class Member Variables

I am trying to make a stl map with key as "KEYWORD" and value as "Class member function" But it is not getting compiled. Following is the code. Can anybody please let me know what is wrong. The class member functions are not static.

typedef void (RemoteHostManager::*CmdHandlerPtr)(char *);
typedef std::map<char *,CmdHandlerPtr> CommandHandlerSet;
typedef std::map<char *,CmdHandlerPtr>::iterator CommandHandlerSetItr;

void RemoteHostManager::InitializeCmdHandlerMap()
{
    m_CommandSet["HELP"]    = &RemoteHostManager::usage;
    m_CommandSet["CONNECT"] = &RemoteHostManager::Connect;
    m_CommandSet["READ"]    = &RemoteHostManager::Read;
    m_CommandSet["WRITE"]   = &RemoteHostManager::Write;
    m_CommandSet["STOP"]    = &RemoteHostManager::Stop;
    m_CommandSet["START"]   = &RemoteHostManager::Start;
}

Following are the errors:

RemoteHostManager.cpp: In member function `void
   RemoteHostManager::InitializeCmdHandlerMap()':
RemoteHostManager.cpp:14: no match for `std::_Rb_tree_iterator<std::pair<const
   std::string, void (RemoteHostManager::*)(char*)>, std::pair<const
   std::string, void (RemoteHostManager::*)(char*)>&, std::pair<const
   std::string, void (RemoteHostManager::*)(char*)>*>& [const char[5]]'
   operator
//similar error for other assignments!

Upvotes: 2

Views: 1425

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361462

typedef std::map<char *,CmdHandlerPtr> CommandHandlerSet;
typedef std::map<char *,CmdHandlerPtr>::iterator CommandHandlerSetItr;

First make it const char*, or even better std::string:

typedef std::map<std::string,CmdHandlerPtr> CommandHandlerSet;
typedef std::map<std::string,CmdHandlerPtr>::iterator CommandHandlerSetItr;

Note all your member functions should match the type of CmdHandlerPtr. That is, the parameter type must be char* , and return type must be void.

When using the map, you need an instance of type RemoteHostManager:

RemoteHostManager instance;
string key;
//...
(instance.*m_CommandSet[key])(param); 

Upvotes: 3

Eric Fortin
Eric Fortin

Reputation: 7603

If class member functions are not static, you need to bind the method with an instance when setting it in the map. You could use boost::bind to do so.

Upvotes: 1

Related Questions