Dynamic mapping of enum value (int) to type

前端 未结 4 1271
清酒与你
清酒与你 2020-12-18 09:27

It appeared that this problem is quite common in our job.

We we are sending an int or enum value through the network, then we receive it we would like to create/call

4条回答
  •  春和景丽
    2020-12-18 10:00

    Try a map:

    struct Base { };
    struct Der1 : Base { static Base * create() { return new Der1; } };
    struct Der2 : Base { static Base * create() { return new Der2; } };
    struct Der3 : Base { static Base * create() { return new Der3; } };
    
    std::map creators;
    
    creators[12] = &Der1::create;
    creators[29] = &Der2::create;
    creators[85] = &Der3::create;
    
    Base * p = creators[get_id_from_network()]();
    

    (This is of course really crude; at the very least you'd have error checking, and a per-class self-registration scheme so you can't forget to register a class.)

提交回复
热议问题