閱讀計算器的一些例子,以下爲一些我以前的問題的答案(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