// Expression template to parse sum a+b+c... // Following Todd Veldhuizen #include #include // The "+" operation. class plus { public: static double apply(double a, double b) { return a+b; }; }; // Node "Left Op Right" template class X { Left left; Right right; public: X(Left l, Right r) : left(l), right(r) { } // initialization list double operator[](int i) { return Op::apply(left[i],right[i]); } // node is indexed with [] ! }; // Simple array class: class Array { std::vector data; public: Array(std::vector d) : data{d} {} // Assign an expression to the array template void operator=(X expression) { for (unsigned i=0; i < data.size(); ++i) data[i] = expression[i]; } double operator[](int i) { return data[i]; } // Array is indexed with [] ! // overload << friend std::ostream& operator <<(std::ostream& os, const Array& obj); }; // overload << for Array output std::ostream& operator<<(std::ostream & os, const Array& obj) { for(auto ele:obj.data) os< X operator+(Left a, Array b) { return X(a,b); } int main() { using std::cout; Array a{{2,3,5,9}}, b{{1,0,0,1}}, c{{3,0,2,5}}, d{{0,0,0,0}}; cout<, plus, Array> // second way: compile a.out and type // nm -C a.out }