将枚举绑定到数组

3

枚举与它们对应的数组之间紧密绑定是否可行?

请注意,以下仅为伪代码,仅用于理解。

方法1:一种方法是我们创建并声明数组。

enum Names
{
    ABC,
    DEF,
    GHI
};

char* names[] = {"abc", "def", "ghl"};      // Declare and define.

要获取值,我们将执行:
char *nm = names[ABC];

这种方法的缺点是我们需要保持枚举和名称数组同步,即如果我们更改枚举并将某些值移动到其他位置,则表格中也需要进行相应的更改。

例如:将DEF移到枚举顶部

枚举名称 { DEF, ABC, GHI };

// 同时更改数组。

char* names[] = {"def", "abc", "ghi"}

方法2。

打破枚举和数组之间的绑定的一种方法是使用下面的创建函数。

int CreateNamesArray() {

      Names[GHI] = "ghl";

      Names[DEF] = "def";

      Names[GHI] = "ghi";

};

现在即使枚举值发生变化,数组也不会受到影响。 这种方法的一个缺点是我们需要在访问表格之前调用该函数。

请建议哪种方法更好。 表格将有30-100个条目。


2
最好的方法是不要有全局数组 :) - Alok Save
或者任何全局变量 - miguel.martin
1
当你说“全局”数组时,你是指具有全局可用的别名/名称的数组索引吗? - DWright
3个回答

4
你可以使用宏来生成它们:
#define LIST \
    PAIR(ABC, "abc") \
    PAIR(DEF, "def") \
    PAIR(GHI, "ghi")

#define PAIR(key, value) key,
enum Names { LIST };
#undef PAIR

#define PAIR(key, value) value,
char* names[] = { LIST };
#undef PAIR

#undef LIST

LIST内部的键值对进行更改来设置键/值对。


1

不使用宏:

#include <iostream>

enum Names { ABC, DEF, GHI };
template< Names n > struct Name { static const char *val; };
template<> const char *Name<ABC>::val = {"abc"};
template<> const char *Name<DEF>::val = {"def"};
template<> const char *Name<GHI>::val = {"ghi"};

int main() {
  std::cout << Name<ABC>::val << std::endl;
  std::cout << Name<DEF>::val << std::endl;
  std::cout << Name<GHI>::val << std::endl;
  return 0;
}

0

我建议使用Boost.Preprocessor来实现:

#include <boost/preprocessor.hpp>
#define DECLARE_PAIRS_ENUM_ELEMENT(r, d, e) BOOST_PP_TUPLE_ELEM(2, 0, e),
#define DECLARE_PAIRS_STRING_ELEMENT(r, d, e) BOOST_PP_TUPLE_ELEM(2, 1, e),
#define DECLARE_PAIRS(n, s) \
    enum n##Names { BOOST_PP_SEQ_FOR_EACH(DECLARE_PAIRS_ENUM_ELEMENT, _, s) }; \
    std::string n##Strings[] = \
    { BOOST_PP_SEQ_FOR_EACH(DECLARE_PAIRS_STRING_ELEMENT, _, s) };
DECLARE_PAIRS(
    someList,
    ((DEF, "ABC"))
    ((ABC, "DEF"))
    ((GHI, "GHI"))
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接