C++11 是否可以在运行时创建枚举类型?

C++11 是否可以在运行时创建枚举类型?,c++11,boost,dynamic,C++11,Boost,Dynamic,在C++11中是否可以执行以下操作 int NED = 3; 或者更有可能 struct EnumMembers { std::string name; }; list<EnumMembers> countries = readafileOfMembers(); say countries list contains "USA", "NOR"; enum CountryType { }; for(auto& c : countries) { Coun

在C++11中是否可以执行以下操作

int NED = 3;
或者更有可能

struct EnumMembers
{
   std::string name;
};


list<EnumMembers> countries = readafileOfMembers();

say countries list contains "USA", "NOR";

enum CountryType
{
};

for(auto& c : countries)
{
    CountryType.Add(c); //since USA first added = 0
}
本质上,枚举是一个必须在编译时填充的容器。我想要一个可以在运行时动态填充的枚举。
也许我不是在寻找一个枚举,而是一个类似于枚举的动态类型。

你在寻找什么取决于它的使用情况。但这并不是很确定。您需要动态数据结构,如
std::map
std::unordered_map
,可能
std::set
您可以搜索
std::set
的示例用法,例如:

enum class Countries
{
  USA =0,
  Canada =1
};


std::set<Countries> countries;
countries.insert(Countries::USA);
countreis.insert(Countries::Canada);
enum类国家/地区
{
美国=0,
加拿大=1
};
std::set国家;
国家。插入(国家:美国);
countreis.插入(国家:加拿大);

或者,当整数值应与国家/地区相关时,您可以使用
无序地图

根据您的问题和评论,我了解您的要求如下:

class Country {
   Country (int numericRepresentation)
     : numericRepresentation(numericRepresentation)
   {
      // setOfLegalInputs could be static
      if(!setOfLegalInputs.contains(numericRepresentation)
      {
          throw TypeError("No such country exists");
      }
   }

   // ...
}
  • 您需要通过限制合法值的范围来实施额外的类型安全性
  • 您希望在运行时确定合法值的范围

在C++之类的静态类型语言中,所有类型检查都在编译时发生,这两个要求是互斥的。(与这种方法可行的动态类型语言相比)

但是,请注意,即使使用动态类型,您也可以实现不变量的运行时验证(例如,在python中,您会得到一个TypeError异常)。显然,您可以通过将国家存储在Bartosz建议的动态数据结构中并创建如下自定义类来模仿这种行为:

class Country {
   Country (int numericRepresentation)
     : numericRepresentation(numericRepresentation)
   {
      // setOfLegalInputs could be static
      if(!setOfLegalInputs.contains(numericRepresentation)
      {
          throw TypeError("No such country exists");
      }
   }

   // ...
}

不,那不是我想要的。不是我解释得不好,就是你不理解我的要求。std::set countries不会在已创建的枚举类型国家/地区上添加额外值。枚举在int上添加类型安全性。我希望能够在运行时创建枚举类型,以便在编译时不知道成员,并且我希望枚举的语义。您可以创建一个为整数建模的结构,但在其下执行额外的域验证。我以前从未见过这样的事。(在C++中),standardizedC++是一种静态类型的编译语言。你不能做那种事。最接近的方法是使用映射从字符串键查找整数值。