fork download
  1. #include <iostream>
  2.  
  3. template<typename T>
  4. class Vector2
  5. {
  6. public:
  7. Vector2(T x, T y)
  8. : x(x), y(y)
  9. {}
  10.  
  11. template<typename U>
  12. Vector2<U> cast() const { return Vector2<U>((U)x, (U)y); }
  13.  
  14. T x;
  15. T y;
  16. };
  17.  
  18. template<typename T>
  19. class Line2
  20. {
  21. public:
  22. Line2(Vector2<T> a, Vector2<T> b)
  23. : a(a), b(b)
  24. {}
  25.  
  26. double gradient() const
  27. {
  28. Vector2<double> ad(a.cast<double>());
  29. Vector2<double> bd(b.cast<double>());
  30.  
  31. return (bd.y - ad.y) / (bd.x - ad.x);
  32. }
  33.  
  34. Vector2<T> a;
  35. Vector2<T> b;
  36. };
  37.  
  38. int main()
  39. {
  40. Vector2<int> intVector(10,5);
  41. Vector2<double> doubleVector(intVector.cast<double>());
  42.  
  43. Line2<int> intLine(Vector2<int>(0,0), Vector2<int>(1,3));
  44. Line2<double> doubleLine(Vector2<double>(0,0), Vector2<double>(0.5,1.23));
  45.  
  46. std::cout << "Line2<int>.gradient = " << intLine.gradient() << std::endl;
  47. std::cout << "Line2<double>.gradient = " << doubleLine.gradient() << std::endl;
  48. }
  49.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In member function ‘double Line2<T>::gradient() const’:
prog.cpp:28:31: error: expected primary-expression before ‘double’
     Vector2<double> ad(a.cast<double>());
                               ^
prog.cpp:28:31: error: expected ‘)’ before ‘double’
prog.cpp:29:31: error: expected primary-expression before ‘double’
     Vector2<double> bd(b.cast<double>());
                               ^
prog.cpp:29:31: error: expected ‘)’ before ‘double’
stdout
Standard output is empty