Dynamically register constructor methods in an AbstractFactory at compile time using C++ templates

后端 未结 7 2033
予麋鹿
予麋鹿 2020-12-02 19:19

When implementing a MessageFactory class to instatiate Message objects I used something like:

class MessageFactory 
{
  public:
    static Message *create(in         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-02 20:04

    2: you could use a dynamic container, but then you'd also had to change how the registration etc. For example, you could use a map with an int as key and a function pointer as element:

    typedef Message* ( *NewMessageFun )();
    
    template< class tMessage >
    Message* NewMessage()
    {
      return new tMessage();
    };
    
    class PingMessage : public MessageImpl
    {
    public:
      enum{ _MESSAGE_ID = 10 };
    };
    
    class PongMessage
    {
    public:
      enum{ _MESSAGE_ID = 11 };
    }
    
    //factory
    std::map< int, NewMessageFun > mymap;
    bool Register( const int type, NewMessageFun fun )
    {
      if( mymap.contains( type ) )
        return false; //already registered!
      mymap[ type ] = fun;
      return true;
    }
    
    template< class tMessage >
    bool RegisterAny() //shortcut
    {
      return Register( tMessage::_MESSAGE_ID, NewMessage< tMessage > );
    }
    //
    
    //main
    factory.RegisterAny< PingMessage >();
    factory.RegisterAny< PongMessage >();
    //
    

    Or, in your current code, just use a sensible allocation size and have runtime bounds checking to see there are too much registrations. And maybe supply an 'Unregister' method.

提交回复
热议问题