fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <cstddef>
  4.  
  5. template <typename T> struct vector_fields_1 { union { T values[1]; struct { T x; }; }; };
  6. template <typename T> struct vector_fields_2 { union { T values[2]; struct { T x, y; }; }; };
  7. template <typename T> struct vector_fields_3 { union { T values[3]; struct { T x, y, z; }; }; };
  8. template <typename T> struct vector_fields_4 { union { T values[4]; struct { T x, y, z, w; }; }; };
  9. template <typename T, std::size_t N> struct vector_fields_n { T values[N]; };
  10.  
  11. template <class T, std::size_t N>
  12. struct vector : public
  13. std::conditional<
  14. N == 1
  15. && offsetof(vector_fields_1<T>, x) == offsetof(vector_fields_1<T>, values[0])
  16. ,
  17. vector_fields_1<T>,
  18. typename std::conditional<
  19. N == 2
  20. && offsetof(vector_fields_2<T>, x) == offsetof(vector_fields_2<T>, values[0])
  21. && offsetof(vector_fields_2<T>, y) == offsetof(vector_fields_2<T>, values[1])
  22. ,
  23. vector_fields_2<T>,
  24. typename std::conditional<
  25. N == 3
  26. && offsetof(vector_fields_3<T>, x) == offsetof(vector_fields_3<T>, values[0])
  27. && offsetof(vector_fields_3<T>, y) == offsetof(vector_fields_3<T>, values[1])
  28. && offsetof(vector_fields_3<T>, z) == offsetof(vector_fields_3<T>, values[2])
  29. ,
  30. vector_fields_3<T>,
  31. typename std::conditional<
  32. N == 4
  33. && offsetof(vector_fields_4<T>, x) == offsetof(vector_fields_4<T>, values[0])
  34. && offsetof(vector_fields_4<T>, y) == offsetof(vector_fields_4<T>, values[1])
  35. && offsetof(vector_fields_4<T>, z) == offsetof(vector_fields_4<T>, values[2])
  36. && offsetof(vector_fields_4<T>, w) == offsetof(vector_fields_4<T>, values[3])
  37. ,
  38. vector_fields_4<T>,
  39. vector_fields_n<T, N>
  40. >::type
  41. >::type
  42. >::type
  43. >::type
  44. {
  45. T& operator[](std::size_t pos) { return this->values[pos]; }
  46. const T& operator[](std::size_t pos) const { return this->values[pos]; }
  47. };
  48.  
  49. int main(int, char**) {
  50. vector<int, 3> obj;
  51. obj[0] = 1;
  52. obj.y = 2;
  53. obj[2] = 3;
  54. std::cout << "(" << obj.x << ", " << obj[1] << ", " << obj.z << ")" << std::endl;
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
(1, 2, 3)