Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <map>
- #include <functional>
- #define ENTITY_BUILDER_DECL(type, typeId) static EntityBuilderTpl<type, typeId> _eb_
- #define ENTITY_BUILDER(type, typeId) EntityBuilderTpl<type, typeId> type::_eb_
- enum EntityType {
- CAR = 0,
- PLANE = 1
- };
- struct EntityBuilder;
- struct Entity {
- static std::map<int, EntityBuilder *> _builders;
- static Entity *build(int typeId);
- };
- std::map<int, EntityBuilder *> Entity::_builders;
- struct EntityBuilder {
- virtual Entity *build() = 0;
- };
- template<class Type, int typeId>
- struct EntityBuilderTpl : public EntityBuilder {
- EntityBuilderTpl() {
- Entity::_builders[typeId] = this;
- }
- Entity *build() {
- return new Type;
- }
- };
- Entity *Entity::build(int typeId)
- {
- auto builder = _builders.find(typeId);
- if (builder != _builders.end()) {
- return builder->second->build();
- } else {
- return nullptr;
- }
- }
- struct Car : public Entity {
- Car() {
- std::cout << "Build car" << std::endl;
- }
- ENTITY_BUILDER_DECL(Car, EntityType::CAR);
- };
- EntityBuilderTpl<Car, EntityType::CAR> _eb_;
- ENTITY_BUILDER(Car, EntityType::CAR);
- struct Plane : public Entity {
- Plane() {
- std::cout << "Build plane" << std::endl;
- }
- ENTITY_BUILDER_DECL(Plane, EntityType::PLANE);
- };
- ENTITY_BUILDER(Plane, EntityType::PLANE);
- int main() {
- EntityType et = CAR;
- Entity::build(CAR);
- Entity::build(CAR);
- Entity::build(PLANE);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement