开发者

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 *);
type开发者_开发百科def 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!


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); 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜