我正在尝试组装枚举(索引)及其相应名称的分层列表,以便我可以按名称访问特定的列表或遍历所有枚举,具体取决于我所在的代码部分。列表将是常量一旦编译,但需要在代码中轻松更改。我正在使用 X 宏来简化这一点,但我有点坚持如何获得我想要的灵活性。也许我做错了。
这部分工作:
namespace another
{
// Define individual groups
//-------------------------
// <<Self>> group
#define XLIST \
X(Lat ) \
X(Lon ) \
X(Altitude ) \
X(Weight )
#define X(a) a,
enum class enum_Self { XLIST NUMEL };
#undef X
#define X(a) #a,
const char * const name_Self[] = { XLIST };
#undef X
#undef XLIST
// <<Target>> group
#define XLIST \
X(Lat ) \
X(Lon ) \
X(Altitude )
#define X(a) a,
enum class enum_Target { XLIST NUMEL };
#undef X
#define X(a) #a,
const char * const name_Target[] = { XLIST };
#undef X
#undef XLIST
// List of the "another" groups
//-----------------------------
#define XLIST \
X(Self ) \
X(Target )
// Group name enumeration
#define X(a) a,
enum class groupEnum { XLIST NUMEL };
#undef X
// Group name strings
#define X(a) #a,
const char * const groupName[] = { XLIST };
#undef X
// An array which contains the number of flags in each group
#define X(a) (const int) another::enum_ ##a::NUMEL,
const int groupSize[] = { XLIST };
#undef X
#undef XLIST
} // end another namespace
然后在 中main
,我可以使用以下方式遍历组:
for (int ii=0; ii<(int)another::groupEnum::NUMEL; ii++)
printf("Group %d is %s\n",ii,(int)another::groupName[ii]);
如果我按名称选择一个特定的组,我可以这样做:
printf("another::enum_Self contains:\n");
for (int ii=0; ii<(int)another::enum_Self::NUMEL; ii++)
printf("\t%s\n",another::name_Self[ii]);
我可以访问这样的特定项目:another::enum_Self::Altitude
问题是我无法遍历每个组,然后遍历该组中的每个项目。我试图创建一个结构数组,每个结构都包含一个enum
和const char * const
数组名称,但我不知道如何预先定义一个通用结构,然后用特定的值对其进行初始化。而且我不能从顶层做一个二维数组,因为不是每个组都有相同数量的项目。我也考虑过向量,但它们是动态的,这里的重点是这些东西一旦编译就根本不应该改变。我怀疑我只是以错误的方式思考问题......