【发布时间】:2011-03-03 02:03:51
【问题描述】:
在阅读了一些关于 stackoverflow 的示例并按照我之前的问题 (1) 的一些答案之后,我最终为此制定了一个“策略”。
我来了:
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)将接口中的函数封装在MACROS内部:
/**
* 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 之上实现一种支持模板的语言。;) 虽然我不知道我认为合适的替代方法,但几乎就是这样根据我的经验,每个人在确实需要模板时都会完成这种模式。
-
我想使用 C++ 是不可能的?
-
是的,C++ 是不可能的。
-
@jer:为什么要发明自己?只需使用Comeau C++。最符合标准的 C++ 编译器带有出色的错误消息并生成 C 代码。
-
老实说,我认为构建一些代码生成器来为您生成数据结构可能更简单。您可以使用类型名称(或任何命名约定)为函数添加前缀。
标签: c++ c templates macros c-preprocessor