fork(2) download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. enum class type {
  6. vector_type,
  7. integer_type
  8. };
  9.  
  10. // Object can either be an Integer or Vector<Object>
  11. class Object {
  12. public:
  13. type type_;
  14. union U {
  15. vector<Object> vec_;
  16. int num_;
  17.  
  18. U() {}
  19.  
  20. U(const vector<int> &vec) : vec_() {
  21. for (size_t i = 0; i < vec.size(); i++) {
  22. vec_.push_back(Object(i));
  23. }
  24. }
  25.  
  26. U(int num) : num_(num) {}
  27.  
  28. U& operator=(const vector<Object>& vec) {
  29. new(&vec_) vector<Object>(vec);
  30. return *this;
  31. }
  32.  
  33. ~U() {}
  34. }u_;
  35.  
  36. Object()
  37. : type_(type::integer_type)
  38. {
  39. }
  40.  
  41. Object(const Object& other)
  42. : type_(other.type_)
  43. {
  44. if(other.type_ == type::vector_type)
  45. u_ = other.u_.vec_;
  46. else
  47. u_.num_ = other.u_.num_;
  48. }
  49.  
  50. Object(const vector<int> &vec)
  51. : type_(type::vector_type),
  52. u_(vec)
  53. {
  54. }
  55.  
  56. Object(int num)
  57. : type_(type::integer_type),
  58. u_(num)
  59. {
  60. }
  61.  
  62. Object& operator=(const Object &other)
  63. {
  64. // Free old vector
  65. if(type_ == type::vector_type)
  66. u_.vec_.~vector();
  67.  
  68. type_ = other.type_;
  69. if(other.type_ == type::vector_type)
  70. u_ = other.u_.vec_;
  71. else
  72. u_.num_ = other.u_.num_;
  73. return *this;
  74. }
  75.  
  76. ~Object() {
  77. if(type_ == type::vector_type)
  78. u_.vec_.~vector();
  79. }
  80. };
  81.  
  82. int main() {
  83. // to construct somth like that: [1,2, [3, [4,5], 6], 7]
  84. Object o(vector<int>({ 1,2 }));
  85.  
  86. return 0;
  87. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Standard output is empty