You can also encapsulate a lot of the iteration logic in a generic base class. Here's a rough example:
Code:
template < typename Derived >
class iterator_interface
{
public:
inline Derived& operator += ( int n )
{
self( ).advance( n );
return self( );
}
inline friend Derived operator + ( Derived const& lhs, int n )
{
return Derived( lhs.self( ) ) += n;
}
inline Derived& operator ++ ( void )
{
return *this += 1;
}
inline Derived operator ++ ( int )
{
Derived
temp = self( );
++*this;
return temp;
}
inline Derived& operator -= ( int n )
{
self( ).advance( -n );
return self( );
}
inline friend Derived operator - ( Derived const& lhs, int n )
{
return Derived( lhs.self( ) ) -= n;
}
inline Derived& operator -- ( void )
{
return *this -= 1;
}
inline Derived operator -- ( int )
{
Derived
temp = self( );
--*this;
return temp;
}
inline friend bool operator == ( Derived const& lhs, Derived const& rhs )
{
return lhs.self( ).compare( rhs ) == 0;
}
inline friend bool operator != ( Derived const& lhs, Derived const& rhs )
{
return lhs.self( ).compare( rhs ) != 0;
}
inline friend bool operator < ( Derived const& lhs, Derived const& rhs )
{
return lhs.self( ).compare( rhs ) < 0;
}
inline friend bool operator <= ( Derived const& lhs, Derived const& rhs )
{
return lhs.self( ).compare( rhs ) <= 0;
}
inline friend bool operator > ( Derived const& lhs, Derived const& rhs )
{
return lhs.self( ).compare( rhs ) > 0;
}
inline friend bool operator >= ( Derived const& lhs, Derived const& rhs )
{
return lhs.self( ).compare( rhs ) >= 0;
}
inline Derived& self( void )
{
return static_cast< Derived& >( *this );
}
inline Derived const& self( void ) const
{
return static_cast< Derived const& >( *this );
}
};
Note that the iterator_interface class doesn't define any dereferencing policies whatsoever, it only provides an interface for iteration. You could of course add that functionality, but I prefer to keep them separate, personally. So to properly inherit from the interface, you just need to define 'advance' and 'compare'. Here's a do-nothing example:
Code:
// minimal interface
class test : public iterator_interface< test >
{
public:
// forward if positive, otherwise reverse
void advance( int n )
{ }
// return 0 if equal, less than 0 if *this precedes rhs, otherwise greater than 0
int compare( test const& rhs ) const
{
return 0;
}
// basic dereferencing
int& operator * ( void )
{
return unused;
}
int const& operator * ( void ) const
{
return unused;
}
int
unused;
};