Skip to content

Template Olympics

Monday, 20 March 2006  |  scott wheeler

I want to have an iterator with an encapsulated "next" function. These iterators will be returned from a class that knows how to advance over the data structure, but that should be completely hidden from the users of the iterator.

Simply declaring the iterator must not require knowledge of the function which is advancing the iterator. (As that will be implementation dependant with multiple implementations. See the create() function in the second example.)

Here's a first implementation that I wrote which violates the line requirement above, but is in pure templates (using a functor):

(Sorry, all of the blank lines get removed by kdedevelopers.org.)


class IntNext { public: IntNext() : m_current(0) {} int operator()() { return m_current++; } private: int m_current; };

template <class T, class Next> class Iterator { public: T next() { return m_next(); } private: Next m_next; };

int main() { Iterator<int, IntNext> it;

std::cout << it.next() << std::endl;
std::cout << it.next() << std::endl;

return 0;

}


Here's an uglier version, which works and meets the requirements, but requires a base class with a virtual member:
template class Next { public: virtual ~Next() {} virtual T next() = 0; };

class IntNext : public Next { public: IntNext() : m_current(0) {} virtual int next() { return m_current++; } private: int m_current; };

template class Iterator { public: Iterator(Next *next) : m_next(next) {} ~Iterator() { delete m_next; } T next() { return m_next->next(); }

private: Next *m_next; };

static Iterator create() { return Iterator(new IntNext); }

int main() { Iterator it = create();

std::cout << it.next() << std::endl;
std::cout << it.next() << std::endl;

return 0;

} That works, but I still don't like it. Anyone that comes up with a pure template way of doing this gets a cookie. For now I'm going to go with the second one just so that I stop screwing with things and can move on with the code, but the floor is open. :-)

Me, aKademy

In other news, no aKademy for me this year. There's exactly one week this summer that I have pre-existing plans and we nailed it. Meh.