Guest User

Untitled

a guest
Nov 26th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <type_traits>
  2.  
  3. template<typename T>
  4. struct Coord
  5. {
  6.     using type = T;
  7.     T x, y;
  8.     Coord(T x = 0, T y = 0) : x(x), y(y) {}
  9. };
  10.  
  11. template<typename T>
  12. struct Point_b : Coord<T>
  13. {
  14.     Point_b(T x = 0, T y = 0) : Coord<T>(x, y) {}
  15. };
  16.  
  17. template<typename T>
  18. struct Vec_b : Coord<T>
  19. {
  20.     Vec_b(T x = 0, T y = 0) : Coord<T>(x, y) {}
  21. };
  22.  
  23. template<typename U, typename T = typename U::type>
  24. struct CoordOps : U
  25. {
  26.     static_assert(std::is_base_of<Coord<T>, U>::value, "not a Coord-based class");
  27.     CoordOps(T x = 0, T y = 0) : U(x, y) {}
  28.     U& operator+=(const Vec_b<T>& r)
  29.     {
  30.         this->x += r.x;
  31.         this->y += r.y;
  32.         return *this;
  33.     }
  34.     U operator+(const Vec_b<T>& r)
  35.     {
  36.         U l(*this);
  37.         l.x += r.x;
  38.         l.y += r.y;
  39.         return l;
  40.     }
  41. };
  42.  
  43. template<typename T> using Point = CoordOps<Point_b<T>>;
  44. template<typename T> using Vec = CoordOps<Vec_b<T>>;
  45.  
  46.  
  47. int main()
  48. {
  49.     using Vecd = Vec<double>;
  50.     using Pointd = Point<double>;
  51.  
  52.     Vecd v1, v2;
  53.     Pointd p1, p2;
  54.  
  55.     v1 += v2;
  56.     auto v3 = v1 + v2;
  57.     p1 += v3;
  58.     p1 += p2; // błąd
  59.     v3 += p2; // błąd
  60.     auto p3 = p1 + p2; // błąd
  61.     auto p4 = v1 + p1; // błąd
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment