#include "iostream"
using namespace std;
enum EnumValue
{
One = 100,
Two,
Three
};
template<class EnumType>
struct EnumValueUnit
{
int indexValue;
EnumType enumValue;
};
#define InvalidateValue ((int)-1)
template<typename EnumType>
EnumType MatchToEnum(int index, const EnumValueUnit<EnumType> *enumMap)
{
size_t i = 0;
for (; enumMap[i].indexValue != InvalidateValue; ++i)
{
if (index == enumMap[i].indexValue)
break;
}
return enumMap[i].enumValue;
}
void main()
{
static EnumValueUnit<EnumValue> testMap[] =
{
1, One,
2, Two,
3, Three,
InvalidateValue, One,
};
EnumValue value = MatchToEnum(2, testMap);
cout << value << endl;
}
using namespace std;
enum EnumValue
{
One = 100,
Two,
Three
};
template<class EnumType>
struct EnumValueUnit
{
int indexValue;
EnumType enumValue;
};
#define InvalidateValue ((int)-1)
template<typename EnumType>
EnumType MatchToEnum(int index, const EnumValueUnit<EnumType> *enumMap)
{
size_t i = 0;
for (; enumMap[i].indexValue != InvalidateValue; ++i)
{
if (index == enumMap[i].indexValue)
break;
}
return enumMap[i].enumValue;
}
void main()
{
static EnumValueUnit<EnumValue> testMap[] =
{
1, One,
2, Two,
3, Three,
InvalidateValue, One,
};
EnumValue value = MatchToEnum(2, testMap);
cout << value << endl;
}
本文介绍了一种使用模板和枚举类型实现的简单高效匹配函数,通过实例展示了如何在C++中利用枚举和模板来简化枚举值到具体对象的映射与查找过程。
1418

被折叠的 条评论
为什么被折叠?



