jeudi 16 janvier 2020

Using templated struct as constructor argument

I have a template class Point which will store x and y coordinates, data type of both can be any arithmetic type.

template <typename T, typename U>
struct Point {
  T x;
  U y;
};

Line class takes two Points as constructor argument to find equation of line.

class Line {
public:
  Line(Point p1, Point p2) {}
};

How can I design Line class so it can accept Point object of different data types?

I have designed something like below, how can I improve it?

template <typename T1, 
          typename T2,
          typename P1 = typename T1::x_type,
          typename P2 = typename T1::y_type,
          typename P3 = typename T2::x_type,
          typename P4 = typename T2::y_type>
class Line {
public:
  Line(Point<P1, P2> p1, Point<P3, P4> p2) {}
};

Aucun commentaire:

Enregistrer un commentaire