/******************************************************************************/
/* */
/* FILE: february.cpp */
/* */
/* How to use template specialization to terminate template recursion */
/* ================================================================== */
/* */
/* Compiled and tested with Visual C++ V6.0 */
/* */
/* V1.00 28-FEB-2002 P. Tellenbach https://www.heimetli.ch/ */
/* */
/******************************************************************************/
#include <iostream>
template< int index >
class Generator
{
private:
char *str ;
public:
Generator( char *s ) : str( s )
{
std::cout.put( str[index+1] ) ;
Generator< index - 2 > generator( s ) ;
}
~Generator()
{
std::cout.put( str[index] ) ;
}
bool operator<( Generator<6> &generator )
{
return 0 ;
}
} ;
template<>
class Generator<0>
{
public:
Generator( char *str )
{
std::cout.put( str[index+1] ) ;
std::cout.put( str[index] ) ;
}
} ;
int main( )
{
return Generator< 4 >( "dl r!o" ) < Generator< 6 >( "ol lwe\nH" ) ;
}
Update 27. February 2022
The compiler complained about constants assigned to nonconst, and about index in the specialized template.
/******************************************************************************/
/* */
/* FILE: february.cpp */
/* */
/* How to use template specialization to terminate template recursion */
/* ================================================================== */
/* */
/* Compiled and tested with Visual C++ V6.0 */
/* */
/* V1.00 28-FEB-2002 P. Tellenbach https://www.heimetli.ch/ */
/* */
/******************************************************************************/
#include <iostream>
template< int index >
class Generator
{
private:
const char *str ;
public:
Generator( const char *s ) : str( s )
{
std::cout.put( str[index+1] ) ;
Generator< index - 2 > generator( s ) ;
}
~Generator()
{
std::cout.put( str[index] ) ;
}
bool operator<( const Generator<6> &generator )
{
return 0 ;
}
} ;
template<>
class Generator<0>
{
public:
Generator( const char *str )
{
std::cout.put( str[1] ) ;
std::cout.put( str[0] ) ;
}
} ;
int main( )
{
return Generator< 4 >( "dl r!o" ) < Generator< 6 >( "ol lwe\nH" ) ;
}