Compile-time iterator type
8/Jan 2008
Something we’ve been wondering at work one day (just for kicks, but being resident template freak I couldnt resist to give it a try). Challenge: given STL collection, find a way to determine ‘compatible’ iterator type for it. Example of intended usage:
std::vector v;
for (ITER_TYPE(int, v)::iterator it = v.begin(); it != v.end(); ++it)
; // do something here.
struct vector_type { char dummy[1]; };
struct list_type { char dummy[2]; };
template vector_type container_type(const std::vector&);
template list_type container_type(const std::list&);
template struct iter_adapter {};
template struct iter_adapter<T, sizeof(vector_type)>
{
typedef typename std::vector::iterator iterator;
typedef typename std::vector::const_iterator const_iterator;
};
template struct iter_adapter<T, sizeof(list_type)>
{
typedef typename std::list::iterator iterator;
typedef typename std::list::const_iterator const_iterator;
};
#define ITER_TYPE(t, c) iter_adapter<c, sizeof(container_type(c))>