Listing 5

template<class TList, class Term> struct SumAndDel;
template<class Term>
struct SumAndDel<NullType,Term>
{
   enum { sum = 0 };
   typedef NullType Result;
};
template<int Coef, class Term, class Tail>
struct SumAndDel<Typelist<Numlist<Coef,Term>,Tail>,Term>
{
private:
   typedef SumAndDel<Tail,Term> temp;
public:
   enum { sum = Coef + temp::sum };
   typedef typename temp::Result Result;
};
template<class Head, class Tail, class Term>
struct SumAndDel<Typelist<Head,Tail>,Term>
{
private:
   typedef SumAndDel<Tail,Term> temp;
public:
   enum { sum = temp::sum };
   typedef Typelist<Head,typename temp::Result> Result;
};

template<class TList> struct Simplify;
template<>
struct Simplify<NullType>
{
   typedef NullType Result;
};
template<int Coef, class T, class Tail>
struct Simplify<Typelist<Numlist<Coef,T>,Tail> >
{
private:
   typedef SumAndDel<Tail,T> temp;
   enum  { newcoef = Coef + temp::sum };
   typedef typename Simplify<
           typename temp::Result>::Result newlist;
public:
   typedef typename Loki::Select<newcoef==0,newlist,
        Typelist<Numlist<newcoef,T>,newlist> >::Result Result;
};