The following program writes a list of integers to standard output; first in normal order, and then in reversed order. The expected output is:
1 2 3 4
4 3 2 1
Unfortunately, it appears that the implementation of reverse<List>
has been lost. Can you fill it in?
#include <iostream>
#include <iterator>
// ----- Unsigned Integer Constants -----
template <size_t I>
struct nat
{
enum { value = I };
};
// ----- Arbitrary Length Lists -----
template <class Head, class Tail>
struct list
{
};
struct nil
{
};
// ----- Copy a list to an output iterator -----
template <class List>
struct copy;
template <class Head, class Tail>
struct copy< list<Head,Tail> >
{
template <class OutputIterator>
static OutputIterator eval(OutputIterator i)
{
*i = Head::value;
return copy<Tail>::eval(++i);
}
};
template <>
struct copy<nil>
{
template <class OutputIterator>
static OutputIterator eval(OutputIterator i)
{
return i;
}
};
// ----- Reverse a list -----
template <class List>
struct reverse;
// ----- Example program -----
int main(int, char * [])
{
typedef list<nat<1>, list<nat<2>, list<nat<3>, list<nat<4>, nil> > > > list;
std::ostream_iterator<size_t> oi(std::cout, " ");
copy<list>::eval(oi);
std::cout << std::endl;
copy<reverse<list>::value>::eval(oi);
return 0;
}