[英]reduce code duplication using macros
I was wondering if someone out there could give me a pointer to reducing duplication when coding. 我想知道是否有人可以给我一个减少编码时重复的指针。
im required to call a function a number of times to populate a structure, for example: 我需要多次调用函数来填充结构,例如:
typedef struct {
uint16_t u16_a;
bool b_org;
char* c_c;
uint16_t u16_d;
} TEntry;
I need to populate each value of these with a function call, although the return values vary, the same function is used for all. 我需要用函数调用填充其中的每个值,尽管返回值有所不同,但所有函数都使用相同的函数。 Would a macro be sufficient to create a template in some way, so that the return type would be dependent on the specific parameter ("string") 宏是否足以以某种方式创建模板,以便返回类型取决于特定的参数(“字符串”)
for example: 例如:
Trrelevant::Trrelevant()
{
TPoint* u_apoint = Insufficient::FindValue("A");
if (u_bpoint != NULL) {
int a = u_apoint;
}
TPoint* p_apoint = Insufficient::FindValue("borg");
if (p_bpoint != NULL) {
bool b = p_bpoint;
}
TPoint* p_cpoint = Insufficient::FindValue("C");
if (etc != NULL) {
char* c = etc;
}
TEct* etc = Insufficient::FindValue("ETC");
if (etc != ETC) {
etc = etc;
}
TEntry entry = {a,
b,
c,
etc};
}
this code is not compiled or accurate, im just trying to illustrate. 此代码未编译或准确,我只是想举例说明。 Im weak in C++ and new to macros, but would anyone know a way to have a macro solve this? 我在C ++中是弱者,对宏还是陌生的,但是谁能知道有一种解决宏的方法吗?
Thank you for your time 感谢您的时间
Recently I had the same kind of issue, I'm not sure what kind of source you use for your inputs. 最近我有同样的问题,那我不知道你用什么样的来源为您的输入。 Personnaly, I used XML as input. 从个性上讲,我使用XML作为输入。 Then I have A Builder class that parses the XML call a factory funciton to build every struct in the c++ using the data from the parser. 然后,我有一个Builder类,该类对XML进行解析,称为工厂函数,以使用解析器中的数据构建c ++中的每个结构。
I don't think that MACRO or templtes would be of any help (or it would be a bad solution). 我认为MACRO或templtes不会有任何帮助(或者这将是一个糟糕的解决方案)。 Note that an external resource (like xml) is nice if ever you want to change without recompiling. 请注意,如果您想更改而无需重新编译,则外部资源(例如xml)是不错的选择。
Best 最好
You could do something like this, although I don't know what it really buys you. 您可以做这样的事情,尽管我不知道它真正为您带来了什么。
#define QuickFindValue(NAME, TYPE, FUNCTION) \
TYPE *NAME##Value = Insufficient::FindValue(#NAME); \
if (NAME##Value == NULL) { FUNCTION; }
You would use it like so: 您可以这样使用它:
QuickFindValue(C, TPoint, {
char *c = CValue;
// Do stuff..
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.