尝试了用C做一个泛型的栈,抛出来跟大家交流一下。
#include <stdio.h>
/**
* Make a struct for stacks.
* I hope to make a generic struct of stacks.
* I may have a try.
*
*/
/** Two variables:
* 01. pointer to char.
* 02. the position of the stack.
* from 0 to MAX
* 03. the length of the array of char which is malloc.;
*/
typedef struct Stack *StackSP;
struct Stack
{
void *pt;
size_t top;
size_t length;
};
/** function judge whether stack is empty.
* argument sp is a pointer to Stack.
*
* should be aware that top is equal to zero while stack is empty.
*/
#define size_t ifempty(StackSP sp) sp->top
/** Push an element into the top of the stack.
*/
#define push(vartype, stacksp, value)\
if(stacksp->top == stacksp->length) fprintf(stderr,"error : stack is full.");\
((vartype *)stacksp->pt)[stacksp->top++] = value ;
/** Pop()function return an element from the top of the stack.
* Warning : the element is also an pointer to void.
* so you cannot referrence the variable by this pointer,
* you show make some conventions.
*/
#define pop(vartype, stacksp)\
(stacksp->top == 0) ? NULL : (((vartype *) stacksp->pt)[--stacksp->top])
/** Free the space applied.
*/
#define closestack(vartype, stacksp) if(stacksp->pt == NULL){\
free((vartype *)stacksp->pt);\
stacksp->top = 0;}
/** Malloc a space for stack.
*
**/
#define openstack(vartype,stacksp,op_length) \
stacksp->pt = malloc(sizeof(vartype) * op_length );\
stacksp->length = op_length; \
stacksp->top = 0;
编译时爆出几个warning,显然用C做泛型还是有些不理智。