I l@ve RuBoard Previous Section Next Section

3.11 Replacing an Element in a Typelist

Sometimes a replacement is needed instead of a removal. As you'll see in Section 3.12, replacing a type with another is an important building block for more advanced idioms.

We need to replace type T with type U in a typelist TList.


   Replace
   Inputs: Typelist TList, type T (to replace), and type U (to replace with)
   Output: Inner type definition Result

   If TList is NullType, then Result is NullType.
   Else
     If the head of the typelist TList is T, then Result is a typelist with U as its head and
       TList::Tail as its tail.
     Else Result is a typelist with TList::Head as its head and the result of applying
       Replace to TListT, and U as its tail.

After you figure out the correct recursive algorithm, the code writes itself:



template <class TList, class T, class U> struct Replace;





template <class T, class U>


struct Replace<NullType, T, U>


{


   typedef NullType Result;


};





template <class T, class Tail, class U>


struct Replace<Typelist<T, Tail>, T, U>


{


   typedef Typelist<U, Tail> Result;


};





template <class Head, class Tail, class T, class U>


struct Replace<Typelist<Head, Tail>, T, U>


{


   typedef Typelist<Head,


         typename Replace<Tail, T, U>::Result>


      Result;


};


We easily obtain the ReplaceAll algorithm by changing the second specialization for one that recursively applies the algorithm to Tail.

    I l@ve RuBoard Previous Section Next Section