fork(1) download
  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4.  
  5. template <int N> struct Array : Array <N - 1>
  6. {
  7. double x;
  8.  
  9. template<int M> double& comp() { return Array<M>::x; }
  10. template<int M> const double& comp() const { return Array<M>::x; }
  11.  
  12. //Prints vector
  13. ostream& print(ostream& out) const
  14. {
  15. static_cast<const Array<N-1>*>(this)->print(out);
  16. out << ", " <<x;
  17. return out;
  18. }
  19.  
  20. double& operator[] (int i) {
  21. return reinterpret_cast<double*>(this)[i];
  22. }
  23.  
  24.  
  25. //Vector in place summation, without looping
  26. Array& operator+=(const Array& v)
  27. {
  28. x+=v.x;
  29. *static_cast<Array<N-1>*>(this) += static_cast<const Array<N-1>&>(v);
  30. return *this;
  31. }
  32. };
  33.  
  34. template <> struct Array<1>
  35. {
  36. double x;
  37.  
  38. template<int M> double& comp() { return Array<M>::x; }
  39. template<int M> const double& comp() const { return Array<M>::x; }
  40.  
  41. //Prints vector
  42. ostream& print(ostream& out) const
  43. {
  44. out << x;
  45. return out;
  46. }
  47.  
  48. double& operator[](int i) {
  49. return *reinterpret_cast<double*>(this);
  50. }
  51.  
  52. //Vector in place summation, without looping
  53. Array& operator+=(const Array& v)
  54. {
  55. x+=v.x;
  56. return *this;
  57. }
  58. };
  59.  
  60. template<int N>
  61. ostream& operator<<(ostream& out, const Array<N>& v)
  62. {
  63. out << "("; v.print(out); out << ")";
  64. return out;
  65. }
  66.  
  67. int main() {
  68. Array<3> vec;
  69.  
  70. vec[0] = 1; vec[1] = 2; vec[2] = 3;
  71.  
  72. cout << vec << endl;
  73.  
  74. cout << (vec+=vec) << endl;
  75.  
  76. return 0;
  77. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
(1, 2, 3)
(2, 4, 6)