protobuf的反射以及protobuf

上一篇提到了protobuf存在的问题

可以使用函数指针替代对象指针的方式来省掉对象带来的额外开销

#include <string>
#include <map>
#include <iostream>
using namespace std;
 
class Message{
public:
    virtual Message* New() = 0;
    virtual string getType() = 0;   
};
 
typedef Message*(CloneFunc)();
class MessageFactory
{
public:
    static MessageFactory* getInstance(){
        static MessageFactory* pMessageFactory = 0;
        if ( pMessageFactory == 0 ) {
            pMessageFactory = new MessageFactory();
        }
        return pMessageFactory;
    }
    void addMessage( const string strType, CloneFunc* pFunc ){
        if ( pFunc )
        {
            m_mapMsgs[strType] = pFunc;
        }       
    }
    Message* getMessage( const string strType) {
        MsgMap::iterator itr = m_mapMsgs.find( strType );
        if ( itr != m_mapMsgs.end() ){
            return (*itr->second)();
        }
        return 0;
    }
private:
    typedef map<string,CloneFunc*> MsgMap;
    MsgMap m_mapMsgs;
};
 
#define DEF_MESSAGE( type ) 
class type : public Message 
{ 
public: 
    virtual Message* New(){ 
        return new type(); 
    } 
    string getType(){ 
        return #type; 
    } 
    static Message* staticCreate(){ 
        return new type(); 
    } 
}; 
class type##_descript{ 
public: 
type##_descript(){ 
    static bool already_here = false; 
    if (already_here) return; 
    already_here = true; 
    MessageFactory::getInstance()->addMessage( #type, &(type::staticCreate) ); 
} 
}; 
type##_descript type##_Descript;
 
DEF_MESSAGE( MyMessage )
 
int _tmain(int argc, _TCHAR* argv[])
{
    Message* pMessage = MessageFactory::getInstance()->getMessage( "MyMessage" );
    cout << pMessage->getType() << endl;
    system( "pause" );
    return 0;
}