阅读计算器的一些例子,以下为一些我以前的问题的答案(1)后,我最终得出了“战略”这个。“模仿”C++模板的C策略是什么?
我已经来到这个:
1)已经在.h
文件声明段。在这里我将定义数据结构和访问接口。例如:
/**
* LIST DECLARATION. (DOUBLE LINKED LIST)
*/
#define NM_TEMPLATE_DECLARE_LIST(type) \
typedef struct nm_list_elem_##type##_s { \
type data; \
struct nm_list_elem_##type##_s *next; \
struct nm_list_elem_##type##_s *prev; \
} nm_list_elem_##type ; \
typedef struct nm_list_##type##_s { \
unsigned int size; \
nm_list_elem_##type *head; \
nm_list_elem_##type *tail; \
int (*cmp)(const type e1, const type e2); \
} nm_list_##type ; \
\
nm_list_##type *nm_list_new_##type##_(int (*cmp)(const type e1, \
const type e2)); \
\
(...other functions ...)
2)裹中相应的界面中宏功能:
/**
* LIST INTERFACE
*/
#define nm_list(type) \
nm_list_##type
#define nm_list_elem(type) \
nm_list_elem_##type
#define nm_list_new(type,cmp) \
nm_list_new_##type##_(cmp)
#define nm_list_delete(type, list, dst) \
nm_list_delete_##type##_(list, dst)
#define nm_list_ins_next(type,list, elem, data) \
nm_list_ins_next_##type##_(list, elem, data)
(...others...)
3)实现以下功能:
/**
* LIST FUNCTION DEFINITIONS
*/
#define NM_TEMPLATE_DEFINE_LIST(type) \
nm_list_##type *nm_list_new_##type##_(int (*cmp)(const type e1, \
const type e2)) \
{\
nm_list_##type *list = NULL; \
list = nm_alloc(sizeof(*list)); \
list->size = 0; \
list->head = NULL; \
list->tail = NULL; \
list->cmp = cmp; \
}\
void nm_list_delete_##type##_(nm_list_##type *list, \
void (*destructor)(nm_list_elem_##type elem)) \
{ \
type data; \
while(nm_list_size(list)){ \
data = nm_list_rem_##type(list, tail); \
if(destructor){ \
destructor(data); \
} \
} \
nm_free(list); \
} \
(...others...)
为了使用那些结构,我要创建两个文件(姑且称之为templates.c
和templates.h
)。
在templates.h
我将不得不NM_TEMPLATE_DECLARE_LIST(int)
,NM_TEMPLATE_DECLARE_LIST(double)
,而在templates.c
我需要NM_TEMPLATE_DEFINE_LIST(int)
,NM_TEMPLATE_DEFINE_LIST(double)
,才能有后面的整数,双打等,生成列表的代码。
通过遵循这个策略,我将不得不将所有的“模板”声明保留在两个文件中,并且在需要数据结构的同时,我需要包含templates.h
。这是一个非常“集中”的解决方案。
你才能知道其他策略,以“模拟”(在某一时刻)的C++模板?你知道的方式来改善这一战略,以保持更分散的方式的东西,所以我不会需要两个文件:templates.c
和templates.h
?
你可以实现一种支持C语言模板的语言; 虽然我不知道另一种方法,但我认为合适,但几乎每个人都可以完成这一任务模式,当他们确实需要模板时,从我的经验。 – jer 2010-06-12 21:08:21
我想使用C++将是不可能的? – 2010-06-12 21:21:36
是的,C++是不可能的。 – 2010-06-12 21:22:47