05 June 2012

C++ Don'ts, Part I

Hello! Today we will be talking about things not to do in C++! Today's topic will be linked lists, more specifically integer linked lists.

We can define a non-null node as follows:

template<int I_, typename T_>
struct Node {
    static const int value = I_;
    static const int size = 1 + Next::size;
    typedef T_ Next;
};

and the null node as follows:

struct End {
    static const int size = 0;
};

We then can implement getting the size of a linked list:

template<typename L_>
struct Size {
    static const int value = L_::size;
};

where L_ is either a Node or an End.

Recursive prints can be done as follows using specialization:

template<typename L_>
struct Print;


template<int I_, typename T_>
struct Print<Node<I_, T_> > {
    static void print() {
        std::cout << I_ << "\n";
        Print<T_>::print();
    }
};


template<>
struct Print {
    static void print() {}
};

See where this is going? Now go implement map, filter, and reduce. :)

No comments:

Post a Comment