利用C++中union的特性,可以将2个参数生成对应类型的唯一key。
如下代码所示,用2个short类型的参数生成一个int类型的key,当param1和param2有一个不同可以生成唯一的key。
应用场景:当读取的配置有一个index和一个sub_index,当index相同时sub_index递增,此时我们将index和sub_index组合就可以生成一个唯一key,用作存储配置map的key。
当获取配置的时侯,我们可以根据index和sub_index生成key从map中找到对应配置。
int ConvertParamToInt(short param1, short param2)
{
union
{
int i_value;
struct
{
short s_value1;
short s_value2;
};
} union_param;
union_param.s_value1 = param1;
union_param.s_value2 = param2;
return union_param.i_value;
}
void ParamIntToValue(const int key, int& param1, int& param2)
{
union
{
int i_value;
struct
{
short s_value1;
short s_value2;
};
} union_param;
union_param.i_value = key;
param1 = union_param.s_value1;
param2 = union_param.s_value2;
}
long long ConvertParamToLongLong(int param1, int param2)
{
union
{
long long ll_value;
struct
{
int i_value1;
int i_value2;
};
} union_param;
union_param.i_value1 = param1;
union_param.i_value2 = param2;
return union_param.ll_value;
}
void ParamLongLongToValue(const long long key, int ¶m1, int ¶m2)
{
union
{
long long ll_value;
struct
{
int i_value1;
int i_value2;
};
} union_param;
union_param.ll_value = key;
param1 = union_param.i_value1;
param2 = union_param.i_value2;
}
long long ConvertParamToLongLong(int param1, short param2, short param3)
{
union
{
long long ll_value;
struct
{
int i_value1;
short s_value2;
short s_value3;
};
} union_param;
union_param.i_value1 = param1;
union_param.s_value2 = param2;
union_param.s_value3 = param3;
return union_param.ll_value;
}
void ParamLongLongToValue(const long long key, int& param1, short& param2,short ¶m3)
{
union
{
long long ll_value;
struct
{
int i_value1;
short s_value2;
short s_value3;
};
} union_param;
union_param.ll_value = key;
param1 = union_param.i_value1;
param2 = union_param.s_value2;
param3 = union_param.s_value2;
}