假设你需要封装如下接口:
cpp
int32_t display_set_hdr_type(const dispmng_display_id id, int32_t value);
int32_t display_set_hdr_match_content(const dispmng_display_id id, int32_t value);
int32_t display_set_hdr_quality(const dispmng_display_id id, int32_t value);
他们的函数实现都非常类似。感觉写起来有许多重复的代码。那么你可以用如下的方式写:
cpp
#define display_set_hdr(name, id, para_type, value) \
int32_t display_set_hdr_##name(const dispmng_display_id id, int32_t value){\
int32_t ret = -1;\
LOGI("display_set_hdr_%s id=%d, value=%d", #name, id, value);\
do {\
uapi_ret_if_invalid_id(id);\
ret = uapi_svr_dispmng_init();\
if (ret != SUCCESS) {\
LOGD("uapi_svr_dispmng_init() failed: %d", ret);\
break;\
}\
ret = uapi_svr_dispmng_set_hdr_##name(id, (para_type)value);\
uapi_svr_dispmng_deinit();\
} while(0);\
return ret;\
}
display_set_hdr(type, id, uapi_svr_dispmng_hdr_type, value)
display_set_hdr(match_content, id, bool, value)
display_set_hdr(quality, id, int32_t, value)
宏展开看一下 gcc -E macro.c -o macro.i
cpp
# 0 "macro.c"
# 0 "<built-in>"
# 0 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 0 "<command-line>" 2
# 1 "macro.c"
# 22 "macro.c"
int32_t display_set_hdr_type(const dispmng_display_id id, int32_t value){ int32_t ret = -1; LOGI("display_set_hdr_%s id=%d, value=%d", "type", id, value); do { uapi_ret_if_invalid_id(id); ret = uapi_svr_dispmng_init(); if (ret != SUCCESS) { LOGD("uapi_svr_dispmng_init() failed: %d", ret); break; } ret = uapi_svr_dispmng_set_hdr_type(id, (uapi_svr_dispmng_hdr_type)value); uapi_svr_dispmng_deinit(); } while(0); return ret;}
int32_t display_set_hdr_match_content(const dispmng_display_id id, int32_t value){ int32_t ret = -1; LOGI("display_set_hdr_%s id=%d, value=%d", "match_content", id, value); do { uapi_ret_if_invalid_id(id); ret = uapi_svr_dispmng_init(); if (ret != SUCCESS) { LOGD("uapi_svr_dispmng_init() failed: %d", ret); break; } ret = uapi_svr_dispmng_set_hdr_match_content(id, (bool)value); uapi_svr_dispmng_deinit(); } while(0); return ret;}
int32_t display_set_hdr_quality(const dispmng_display_id id, int32_t value){ int32_t ret = -1; LOGI("display_set_hdr_%s id=%d, value=%d", "quality", id, value); do { uapi_ret_if_invalid_id(id); ret = uapi_svr_dispmng_init(); if (ret != SUCCESS) { LOGD("uapi_svr_dispmng_init() failed: %d", ret); break; } ret = uapi_svr_dispmng_set_hdr_quality(id, (int32_t)value); uapi_svr_dispmng_deinit(); } while(0); return ret;}
是不是觉得#跟##用起来很清爽了?