// C++ iteration. Based on Alexandrescu's "range" concept. #include // range: generate a sequence of numbers, modeled after Python. template class Range { private: T cur, end, step; public: Range(const T _start, const T _end, const T _step): cur(_start), end(_end), step(_step) {} bool nil() const { return cur == end; } T first() const { return cur; } void next() { cur += step; } typedef T elem; }; template inline Range range(const T _start, const T _end, const T _step) { return Range(_start, _end, _step); } template inline Range range(const T _start, const T _end) { return range(_start, _end, T(1)); } template inline Range range(const T _end) { return range(T(0), _end); } // map: transform each element of a sequence with a function template class Map { private: I iter; F func; public: Map(I _iter, F _func): iter(_iter), func(_func) {} bool nil() const { return iter.nil(); } typedef typename F::return_type elem; elem first() const { return func(iter.first()); } void next() { iter.next(); } }; template inline Map map(const I _iter, const F _func) { return Map(_iter, _func); } // for_each: call a function for each item of a sequence template void for_each(I seq, F f) { for (; !seq.nil(); seq.next()) f(seq.first()); } // Example application logic: IntPrinter and Squarer class IntPrinter { public: void operator()(int x) const { std::cout << x << " "; } }; class Squarer { public: typedef int return_type; return_type operator()(int x) const { return x * x; } }; int main () { for_each(map(range(10), Squarer()), IntPrinter()); std::cout << "\n"; return 0; }