stackoverflow에 대한 몇 가지 예제를 읽고 이전 질문 (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.c
에서 내가하는 int, 복식 등, 생성 된 목록 뒤에 코드를 위해, NM_TEMPLATE_DEFINE_LIST(int)
, NM_TEMPLATE_DEFINE_LIST(double)
필요합니다 동안
templates.h
에서 나는,
NM_TEMPLATE_DECLARE_LIST(int)
,
NM_TEMPLATE_DECLARE_LIST(double)
해야합니다.
이 전략을 따르면 모든 "템플릿"선언을 두 파일로 유지해야하며 동시에 데이터 구조가 필요할 때마다 templates.h
을 포함해야합니다. 매우 "중앙 집중화 된"솔루션입니다.
C + +에서 템플릿을 "모방"(어떤 시점에서)하기 위해 다른 전략을 알고 있습니까? 보다 분산 된 방식으로 작업을 유지하기 위해이 전략을 개선하는 방법을 알고 있으므로 두 파일이 필요하지 않습니다 : templates.c
및 templates.h
? 자신을 저장
당신은 C의 위에 템플릿을 지원하는 언어를 구현할 수 있습니다;) 제가 적합하다고 생각하는 머리 위로 떨어져있는 대체 방법을 알지 못하지만 거의 모든 사람들이 이것을 수행하는 방법입니다 내 경험에 따라 템플릿이 필요한 패턴. – jer
C++을 사용하는 것이 궁금 할 것 같습니까? –
예, C++이 궁금합니다. –