Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> How do you write containers? I tried following a series on implementing an interpreter in c a few months ago, but gave up because 30% of the code was implementing std::vector for different types.

You can use the preprocessor to generate these discrete functions and data structures. A simple example implementing just a linked list data structure:

list_generic.h:

    #define CATH(a, b) a ## b
    #define CAT(a, b) CATH(a, b)

    struct CAT(T, _list) {
        T value;
        struct CAT(T, _list) *tail;
    };
list.h:

    #define T int
    #include "list_generic.h"
    #undef T

    #define T float
    #include "list_generic.h"
    #undef T

    typedef char * string;
    #define T string
    #include "list_generic.h"
    #undef T
Then you'll end up with int_list, float_list and string_list structs.

Not saying that this is pretty or particularly satisfies the goal of being explicit and readable, but it's possible if you can accept different type and method names for the different contained types.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: