Listing 3: New template implementation
class RegularExpression
{
public:
virtual ~RegularExpression() {}
virtual RegularExpression * RepeatMe()
{
throw std::exception( "I cannot repeat" );
}
virtual bool Interpret( const char *& ) const = 0;
};
template< typename RE >
class Repeater : public RegularExpression
{
RE * repeat_;
public:
Repeater( RE * repeat )
: repeat_( repeat ) {}
virtual bool Interpret( const char *& sz ) const
{
while( repeat_->RE::Interpret( sz ) )
;
return true;
}
};
class LiteralExpression : public RegularExpression
{
char ch_;
public:
LiteralExpression( char ch )
: ch_( ch ) {}
virtual Repeater<LiteralExpression> * RepeatMe()
{
// I repeat myself.
return new Repeater<LiteralExpression>( this );
}
virtual bool Interpret( const char *& sz ) const
{
return ( *sz == ch_ ) ? ( ++sz, true ) : false;
}
};
End of Listing