在编写这个项目时,我遇到了一个需要能够同时处理uint8_t,uint16_t和uint32_t变量的函数的情况.
我试图找到一个合适的解决方案,以保持这种动态,而不会造成太多的混乱或大量的重复代码,但最重要的是,有一个保存解决方案.
在当前代码中,我使用带有union作为函数参数的结构:
typedef struct
{
DataType type;
union
{
uint8_t uint8;
uint16_t uint16;
uint32_t uint32;
} unsignedInt;
} anySizeUnsignedType;
Run Code Online (Sandbox Code Playgroud)
这是尝试使函数更加动态,但是,我的函数中有2个这样的类型,需要根据第三个变量进行比较.
所以,这基本上就是我要做的事情:
anySizeUnsignedType Var1 = arg1;
anySizeUnsignedType Var2 = arg2;
uint8_t comparison = arg3;
switch (comparison)
{
case ABOVE:
if (Var1 > Var2 )
{
retValue = TRUE;
}
break;
case EQUAL:
if (Var1 > (Var2 - AnotherVar)
&& (Var1 < (Var2 + AnotherVar)))
{
retValue = TRUE;
}
break;
case BELOW:
if (Var1 < Var2 )
{
retValue = TRUE;
}
break;
default:
/* Should be impossible */
break;
}
Run Code Online (Sandbox Code Playgroud)
问题:我无法比较"Var",因为它当然是一个结构,我需要比较uint8_t,uint16_t或uint32_t,但有没有办法做到这一点保存没有相同的代码3次所有3无符号类型?
或者是否有更好的解决方案来做到这一点?或者也许是不想这样做的理由?
我正在尝试这个的原因:处理来自不同传感器的传感器数据,不同的输出并保持自己的官方分辨率,
我倾向于使用
int compare(uint32_t arg1, uint32_t arg2, uint8_t comparison)
作为(单个)函数,并依赖于类型扩展的较窄版本arg1和arg2.