C ++ meta Programming to create a new list of types with remove_const applied to each element

Hey. Can anyone give me a sample program "Create ApplyRemoveConst Template That Creates A New List Of Types With Remove_const Applied To Each Item"

For instance:

typedef TYPELIST_3(A, const B, B) TL;
typedef ApplyRemoveConst<TL>::Result TL2;
// TL2 is the same as TYPELIST_3(A, B, B)


//Typelist Definition:

template<class T, class U>
struct Typelist
{
    typedef T Head;
    typedef U Tail;
    // Lets us a print a typelist
    inline static ostream &print(ostream &os) {
        return printInternal(os, "[");
    }
    inline static ostream &printInternal(ostream &os, string delimiter) {
        os << delimiter << typeid(Head).name();
        return Tail::printInternal(os, ", ");
    }
private:
    Typelist(); // Cannot create!
};

#define TYPELIST_1(T1)  Typelist<T1, NullType>
#define TYPELIST_2(T1, T2) Typelist<T1, TYPELIST_1(T2)>
#define TYPELIST_3(T1, T2, T3) Typelist<T1, TYPELIST_2(T2, T3)>

// Null type definition 

class NullType{
public:
    // NullType ends a typelist (just like NULL ends a C string)
    inline static ostream &printInternal(ostream &os, string delimiter) {
        return os << "]";
    }
};

      

+2


a source to share


1 answer


I think you want something like this:

template <typename, template <typename> class>
struct transform;

template <template <typename> class Func>
struct transform<NullType, Func>
{
    typedef NullType type; // nothing to do
};

template <typename T, typename U, template <typename> class Func>
struct transform<Typelist<T, U>, Func>
{
    typedef typename Func<T>::type Head; // apply to head
    typedef typename transform<U, Func>::type Tail; // tail is transformed tail

    typedef Typelist<Head, Tail> type; // put together
};

      

This is something recursive. He makes a new list by applying it to the head, then applying everything else like a tail. This in turn imposes the head, etc., until it is reached NullType

, in which we simply get NullType

.

Then you just need a meta functor:



template <typename T>
struct remove_const
{
    typedef T type;
};

template <typename T>
struct remove_const<const T>
{
    typedef T type;
};

      

Then put them together:

typedef TYPELIST_3(A, const B, B) TL;
typedef transform<TL, remove_const>::type TL2;
// TL2 is the same as TYPELIST_3(A, B, B)

      

It should be noted that I have not tried any of this.

+4


a source







All Articles