• Kernel.h

    namespace GateServer { class CKernel { using PFMsgHandler = std::function<bool(const char * pMsg, int MsgLen)> public: bool Initialize(); PFMsgHandler m_MsgHandler[100]; bool OnMsgFromCS(const char * pMsg, int MsgLen); } } 
  • Kernel.cpp

     #include "Kernel.h" namespace GateServer { bool CKernel::Initialize() { m_MsgHandler[0] = &CKernel::OnMsgFromCS; //error return true; } } 

When I try to compile a program, I get the following error:

Error C2679 binary '=': operator ol ol (__thiscall GateServer :: CGSKernel :: *) (const char *, int) ' \ projects \ c ++ \ sonic \ server \ gateserver \ gskernel \ gskernel.cpp 28

    3 answers 3

    You are trying to assign std::function pointer to a member of a class.

    You can solve the problem in one of two ways:

    1. PFMsgHandler pointer:

       namespace GateServer { class CKernel { using PFMsgHandler = bool(GateServer::*)(const char * pMsg, int MsgLen); // ... 
    2. Or enclose a pointer inside an instance of std::function :

       #include "Kernel.h" namespace GateServer { bool CKernel::Initialize() { m_MsgHandler[0] = std::bind( &CKernel::OnMsgFromCS, this, std::placeholders::_1, std::placeholders::_2 ); return true; } } 

      Non-static class methods are not ordinary functions. In particular, every non-static class method conceptually has a hidden parameter ClassType *this .

      In your case, the CKernel::OnMsgFromCS actually has three parameters: CKernel *this , const char * pMsg and int MsgLen . You try to thrust the pointer on this method into std::function , which has only two parameters. Therefore, an error occurs.

      And how to correct this error depends on what you are trying to do.

        There is a third solution, for which you need to slightly modify the PFMsgHandler :

         using PFMsgHandler = std::function<bool(CKernel&, const char * pMsg, int MsgLen)> 

        And when you call an instance of PFMsgHandler you will need to pass an object for which the class function should be called, for example:

         m_MsgHandler[0](*this, "Message", 0); 

        Of course, you can use a pointer in the PFMsgHandler definition, not a link, which will be more convenient with this , but less convenient with objects that are not pointers.