Advertisement
Masadow

C++ simple reflection

Jan 30th, 2019
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <functional>
  4.  
  5. #define ENTITY_BUILDER_DECL(type, typeId) static EntityBuilderTpl<type, typeId> _eb_
  6. #define ENTITY_BUILDER(type, typeId) EntityBuilderTpl<type, typeId> type::_eb_
  7.  
  8. enum EntityType {
  9.     CAR = 0,
  10.     PLANE = 1
  11. };
  12.  
  13. struct EntityBuilder;
  14.  
  15. struct Entity {
  16.     static std::map<int, EntityBuilder *> _builders;
  17.  
  18.     static Entity *build(int typeId);
  19.  
  20. };
  21.  
  22. std::map<int, EntityBuilder *> Entity::_builders;
  23.  
  24. struct EntityBuilder {
  25.     virtual Entity *build() = 0;
  26. };
  27.  
  28. template<class Type, int typeId>
  29. struct EntityBuilderTpl : public EntityBuilder {
  30.     EntityBuilderTpl() {
  31.         Entity::_builders[typeId] = this;
  32.     }
  33.  
  34.     Entity *build() {
  35.         return new Type;
  36.     }
  37. };
  38.  
  39. Entity *Entity::build(int typeId)
  40. {
  41.     auto builder = _builders.find(typeId);
  42.     if (builder != _builders.end()) {
  43.         return builder->second->build();
  44.     } else {
  45.         return nullptr;
  46.     }
  47. }
  48.  
  49.  
  50. struct Car : public Entity {
  51.  
  52.     Car() {
  53.         std::cout << "Build car" << std::endl;
  54.     }
  55.  
  56.     ENTITY_BUILDER_DECL(Car, EntityType::CAR);
  57. };
  58.  
  59. EntityBuilderTpl<Car, EntityType::CAR> _eb_;
  60.  
  61. ENTITY_BUILDER(Car, EntityType::CAR);
  62.  
  63. struct Plane : public Entity {
  64.     Plane() {
  65.         std::cout << "Build plane" << std::endl;
  66.     }
  67.  
  68.     ENTITY_BUILDER_DECL(Plane, EntityType::PLANE);
  69. };
  70.  
  71. ENTITY_BUILDER(Plane, EntityType::PLANE);
  72.  
  73. int main() {
  74.     EntityType et = CAR;
  75.  
  76.     Entity::build(CAR);
  77.     Entity::build(CAR);
  78.     Entity::build(PLANE);
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement