/* This program reads a stream of int values and prints the sum. * The loop is in the copy algorithm which can copy to any object * with operator* and operator++ methods. * The summation object is behaving like an iterator. * Because the summation object is copied the instance variables * sum and next need to be outside the object :(. */ #include #include // copy #include template class summation { T &sum, &next; public: summation(T& ps, T& pn):sum(ps), next(pn) {} T & operator* (){ return next; } // will be assigned next input value summation& operator++ () { sum += next; return *this;} }; int main() { int next, sum=0; // used by summation std::istream_iteratorfirst(std::cin), last; std::copy(first, last, summation(sum, next) ); std::cout << sum << "\n"; }