fork(2) download
  1. #include <initializer_list>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. template <typename L, typename Op, typename R>
  6. class Expression
  7. {
  8. public:
  9. Expression(L const& l, R const& r) : l_(l), r_(r) {}
  10.  
  11. typename L::value_type operator[](std::size_t i) const
  12. {
  13. return Op::Apply(l_[i], r_[i]);
  14. }
  15.  
  16. private:
  17. L const& l_;
  18. R const& r_;
  19. };
  20.  
  21. struct Plus
  22. {
  23. template <typename T>
  24. static T Apply(T l, T r) { return l + r; }
  25. };
  26.  
  27. template <class L, class R>
  28. inline Expression<L, Plus, R> operator+(L const& lhs, R const& rhs)
  29. {
  30. return Expression<L, Plus, R>(lhs, rhs);
  31. }
  32.  
  33. template <typename T>
  34. struct Vector
  35. {
  36. using value_type = T;
  37.  
  38. std::vector<T> v_;
  39.  
  40. Vector(std::initializer_list<T> il)
  41. : v_(il.begin(), il.end()) {}
  42.  
  43. template <typename E>
  44. Vector& operator=(E const& r)
  45. {
  46. for (std::size_t i = 0; i < v_.size(); ++i) operator[](i) = r[i];
  47. return *this;
  48. }
  49.  
  50. T& operator[](std::size_t i) { return v_[i]; }
  51.  
  52. T const& operator[](std::size_t i) const { return v_[i]; }
  53. };
  54.  
  55. int main()
  56. {
  57. Vector<int> l{ 1, 2, 3 };
  58. Vector<int> r{ 4, 5, 6 };
  59.  
  60. Vector<int> v{ 0, 0, 0 };
  61. v = l + r;
  62.  
  63. for(auto j : v.v_) std::cout << j << std::endl;
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 4380KB
stdin
Standard input is empty
stdout
5
7
9