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