Search code examples
ctemplatesgccprecompile

template implemation compatible for pointer in c


#define MAX_SIZE 32
#define DECLEAR_RINGQUEUE(type) \
typedef struct RINGQUEUE_##type{ \
    type data[MAX_SIZE]; \
}RINGQUEUE_##type; \
...someMethod

DECLEAR_RINGQUEUE(structA)
DECLEAR_RINGQUEUE(int*)

the character '*' affect the name of structure, how can i fix this.. any preprocessor directive available? or i must redeclare other definition like

#define DECLEAR_RINGQUEUE_ptr(type) \
typedef struct RINGQUEUE_##type{ \
    type* data[MAX_SIZE]; \
}RINGQUEUE_##type; \

Solution

  • Using "naked" types, I don't think you can do it without the extra macro, since int and * are two separate tokens.

    So your separate macro is a possibility, but I would make a slight change to differentiate between int and int*:

    #define DECLEAR_RINGQUEUE_ptr(type) \
        typedef struct RINGQUEUE_ptr_##type{ \
            type *data[MAX_SIZE]; \
        } RINGQUEUE_ptr_##type;
    

    As you currently have it, both would create the same struct and typedef names, leading to errors.


    However, if you typedef the pointer type first so it's presented as one token, you could use something like:

    typedef int* pInt;
    DECLEAR_RINGQUEUE(pInt);
    

    That should work, based on the fact that the following code:

    #define MAX_SIZE 32
    
    #define DECLEAR_RINGQUEUE(type) \
        typedef struct RINGQUEUE_##type { \
            type data[MAX_SIZE]; \
        } RINGQUEUE_##type
    
    DECLEAR_RINGQUEUE(int);
    
    typedef int* pInt;
    DECLEAR_RINGQUEUE(pInt);
    

    generates, when passed through the pre-processor:

    typedef struct RINGQUEUE_int { int data[32]; } RINGQUEUE_int;
    
    typedef int* pInt;
    typedef struct RINGQUEUE_pInt { pInt data[32]; } RINGQUEUE_pInt;
    

    and compiles without error.