fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. struct Coordinate
  5. {
  6. double x;
  7. double y;
  8. Coordinate(double x, double y) : x(x), y(y) {}
  9. };
  10.  
  11. Coordinate operator*(double d, Coordinate c)
  12. { return {c.x*d, c.y*d}; }
  13.  
  14. Coordinate operator*(Coordinate c, double d)
  15. { return d*c; }
  16.  
  17. Coordinate operator+(Coordinate lhs, Coordinate rhs)
  18. { return {lhs.x +rhs.x, lhs.y + rhs.y}; }
  19.  
  20. std::ostream& operator<<(std::ostream& out, const Coordinate& c)
  21. { return out << '(' << c.x << ", " << c.y << ')'; }
  22.  
  23. class Line
  24. {
  25. public:
  26. Line(const Coordinate& start, const Coordinate& end)
  27. : mP1(start), mP2(end)
  28. {}
  29.  
  30. std::function<Coordinate(double)> get_path() const
  31. {
  32. return [this](double t) {
  33. return (1-t)*this->mP1 + t*this->mP2;
  34. };
  35. }
  36. private:
  37. Coordinate mP1;
  38. Coordinate mP2;
  39. };
  40.  
  41. struct Movable {
  42. std::function<Coordinate(double)> mpPath;
  43.  
  44. template<typename T>
  45. void setPath(const T& obj)
  46. {
  47. mpPath = obj.get_path();
  48. }
  49.  
  50. Coordinate position(double d)
  51. {
  52. return mpPath(d);
  53. }
  54. };
  55.  
  56. int main()
  57. {
  58. Line my_line(Coordinate(0.0, 0.0),
  59. Coordinate(10.0, 10.0));
  60. Movable object2;
  61. object2.setPath(my_line);
  62. std::cout << object2.position(0.5); // prints (5, 5)
  63. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
(5, 5)