Sorry for my poor English. I want to decouple receiving data and processing data, this is the demo code:
#include<memory>
#include<iostream>
#include<functional>
using message_handler=std::function<void(const std::string&)>;
class Session: public std::enable_shared_from_this<Session>
{
class PacketProc
{
public:
void SetOnMsgProc(const message_handler &&on_msg_func)
{
this->inner_on_msg_func = on_msg_func;
}
void ProcRcved(const std::string &str)
{
if(inner_on_msg_func)
{
inner_on_msg_func(str);
}
}
private:
message_handler inner_on_msg_func;
};
public:
~Session()
{
std::cout << "~Session()" << std::endl;
}
void Init(void)
{
std::weak_ptr<Session> weak=shared_from_this();
packet_proc.SetOnMsgProc([weak](const std::string & str){
auto shared = weak.lock();
if(shared && shared->outter_on_msg_func)
{
shared->outter_on_msg_func(str);
}
});
outter_on_msg_func= [](const std::string & str)
{
std::cout << "recieved:" << str << std::endl;
};
}
void Proc(void)
{
std::string str = read();
packet_proc.ProcRcved(str);
}
std::string read(void)
{
return std::string("this is a test");
}
private:
PacketProc packet_proc;
message_handler outter_on_msg_func;
};
int main()
{
std::shared_ptr<Session> pSession= std::make_shared<Session>();
pSession->Init();
pSession->Proc();
}
Any suggestion and advice is welcome.