fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. #define PROPERTY_TYPES \
  6.   X(CAR, "A Car") \
  7.   X(HOUSE, "A House") \
  8.   X(ISLAND, "An Island") // <-- add more types
  9.  
  10. #define X(type, name) type,
  11. enum class property_type : size_t
  12. {
  13. PROPERTY_TYPES
  14. };
  15. #undef X
  16.  
  17. #define X(type, name) name,
  18. const char *property_name[] =
  19. {
  20. PROPERTY_TYPES
  21. };
  22. #undef X
  23.  
  24. class Property
  25. {
  26. public:
  27. virtual property_type type() = 0;
  28. };
  29.  
  30. class Car : public Property
  31. {
  32. public:
  33. Car(std::string name) : mName(name) {}
  34. std::string mName;
  35. property_type type() { return property_type::CAR; }
  36. };
  37.  
  38. class House : public Property
  39. {
  40. public:
  41. House(std::string name) : mName(name) {}
  42. std::string mName;
  43. property_type type() { return property_type::HOUSE; }
  44. };
  45.  
  46. class Person
  47. {
  48. public:
  49. std::vector< std::shared_ptr<Property> > properties;
  50. };
  51.  
  52. std::ostream& operator<< (std::ostream& os, property_type type)
  53. {
  54. os << property_name[static_cast<size_t>(type)];
  55. return os;
  56. }
  57.  
  58. int main()
  59. {
  60. Person x;
  61. auto y = std::shared_ptr<Property>(new Car("my car"));
  62. auto z = std::shared_ptr<Property>(new House("my house"));
  63. x.properties.push_back(y);
  64. x.properties.push_back(z);
  65. for (auto i : x.properties)
  66. {
  67. std::cout << i->type() << std::endl;
  68. }
  69. return 0;
  70. }
Success #stdin #stdout 0s 4256KB
stdin
Standard input is empty
stdout
A Car
A House