fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. namespace vector
  5. {
  6. class float2
  7. {
  8. public:
  9. float2(float x,float y):x(x),y(y)
  10. {}
  11. float x, y;
  12. };
  13. class float3
  14. {
  15. public:
  16. union {
  17. struct {
  18. float x,y,z;
  19. };
  20. float f[3];
  21. };
  22.  
  23. public:
  24. float3(float x,float y,float z):x(x),y(y),z(z)
  25. {}
  26.  
  27. float2 swizzle_xx() const;
  28. float3 swizzle_xxx() const;
  29. float3 swizzle_yzx() const;
  30. const float3 &swizzle_xyz() const;
  31. float3 &swizzle_xyz();
  32. float2 &swizzle_yz();
  33. };
  34.  
  35. namespace detail {
  36. template <int X, int Y>
  37. float2 swizzle2(const float3 &v)
  38. {
  39. static_assert(X < 3 && Y < 3, "");
  40. return float2(v.f[X], v.f[Y]);
  41. }
  42. template <int X, int Y, int Z>
  43. float3 swizzle3(const float3 &v)
  44. {
  45. static_assert(X < 3 && Y < 3 && Z < 3, "");
  46. return float3(v.f[X], v.f[Y], v.f[Z]);
  47. }
  48. }
  49.  
  50. // 結果がfloat2
  51. float2 float3::swizzle_xx() const {return detail::swizzle2<0, 0>(*this);}
  52. float2 &float3::swizzle_yz() {return reinterpret_cast<float2 &>(y);}
  53.  
  54. // 結果がfloat3
  55. float3 float3::swizzle_xxx() const {return detail::swizzle3<0, 0, 0>(*this);}
  56. float3 float3::swizzle_yzx() const {return detail::swizzle3<1, 2, 0>(*this);}
  57. const float3 &float3::swizzle_xyz() const {return *this;}
  58. float3 &float3::swizzle_xyz() {return *this;}
  59. }
  60.  
  61. #define xxx swizzle_xxx()
  62. #define yzx swizzle_yzx()
  63. #define xyz swizzle_xyz()
  64. #define xx swizzle_xx()
  65. #define yz swizzle_yz()
  66.  
  67.  
  68. int main() {
  69. // your code goes here
  70. using namespace vector;
  71. float3 a(1,2,3);
  72. auto b=a.yzx;
  73. cout<<b.x<<b.y<<b.z<<endl;
  74.  
  75. b.yz = a.xx;
  76. cout<<b.x<<b.y<<b.z<<endl;
  77. return 0;
  78. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
231
211