要求:
- 必须能够使用 C 字符串以及 C++ 字符串
- 快速地
- 没有地图
- 没有模板
- 没有直接查找,即索引可能超出范围。
- 索引不连续
- 一个头文件中包含的枚举和字符串
- 仅实例化您使用的内容。
到目前为止,这是我想出的:
- test.hh -
// Generic mapper
//
// The idea here is to create a map between an integer and a string.
// By including it inside a class we prevent every module which
// includes this include file from creating their own instance.
//
struct Mapper_s
{
int Idx;
const char *pStr;
};
// Status
enum State_t
{
Running = 1,
Jumping = 6,
Singing = 12
};
struct State_s
{
static const Mapper_s *GetpMap(void)
{
static Mapper_s Map[] =
{
{ Running, "Running" },
{ Jumping, "Jumping" },
{ Singing, "Singing" },
{ 0, 0}
};
return Map;
};
};
- test.cc -
// This is a generic function
const char *MapEnum2Str(int Idx, const Mapper_s *pMap)
{
int i;
static const char UnknownStr[] = "Unknown";
for (i = 0; pMap[i].pStr != 0; i++)
{
if (Idx == pMap[i].Idx)
{
return pMap[i].pStr;
}
}
return UnknownStr;
}
int main()
{
cout << "State: " << MapEnum2Str(State, State_s::GetpMap()) << endl;
return 0;
}
关于如何改进这一点的任何建议?
感觉头文件看起来有点杂乱...