c++ - 编译时检查字符串到枚举映射是否完整

标签 c++ string map c++11 enums

这个问题很可能是 "How to map strings to enums" 的第 n 次迭代.

我的要求更进一步,当在有效输入范围内找不到键时,我想抛出一个特定的异常。所以我有这个 EnumMap 的实现(需要提升 const std::map 定义):

#include <map>
#include <string>
#include <sstream>
#include <stdexcept>
#include <boost/assign.hpp>

typedef enum colors {
  RED,
  GREEN,
} colors;
// boost::assign::map_list_of
const std::map<std::string,int> colorsMap  = boost::assign::map_list_of
                                            ("red",   RED)
                                            ("green", GREEN);
//-----------------------------------------------------------------------------
// wrapper for a map std::string --> enum
class EnumMap {
 private:
  std::map<std::string,int> m_map;
  // print the map to a string
  std::string toString() const {
    std::string ostr;
    for(auto x : m_map) {
      ostr += x.first + ", ";
    }
    return ostr;
  }
 public:
  // constructor
  EnumMap(const std::map<std::string,int> &m) : m_map(m) { }
  // access
  int at(const std::string &str_type) {
    try{
      return m_map.at(str_type);
    }
    catch(std::out_of_range) {
      throw(str_type + " is not a valid input, try : " + toString());
    }
    catch(...) {
      throw("Unknown exception");
    }
  }
};
//-----------------------------------------------------------------------------
int main()
{
  EnumMap aColorMap(colorsMap);
  try {
    aColorMap.at("red");    // ok
    aColorMap.at("yellow"); // exception : "yellow is not a valid input ..."
  }
  catch(std::string &ex) {
    std::cout << ex << std::endl;
  }
  return 0;
}

这很好用,可以满足我的需要。现在,我想在编译时知道某个 enum 中的所有元素都被传递给 EnumMap 构造函数,并且还知道enum 与相应的字符串匹配。

我试过 std::initializer_liststatic_assert , 但 VC2010 似乎仍然不支持 std::initializer_list(参见 here)。

有没有人知道如何实现它?也许使用模板,或者实现我自己的 Enum 类?

最佳答案

typedef enum colors {
  MIN_COLOR,
  RED = MIN_COLOR,
  GREEN,
  MAX_COLOR
} colors;

template< colors C >
struct MapEntry {
  std::string s;
  MapEntry(std::string s_):s(s_) {}
};
void do_in_order() {}
template<typename F0, typename... Fs>
void do_in_order(F0&& f0, Fs&&... fs) {
  std::forward<F0>(f0)();
  do_in_order( std::forward<Fs>(fs)... );
}
struct MapInit {
  std::map< std::string, color > retval;
  operator std::map< std::string, color >() {
    return std::move(retval);
  }
  template<colors C>
  void AddToMap( MapEntry<C>&& ent ) {
    retval.insert( std::make_pair( std::move(end.s), C ) );
  }
  template< typename... Entries >
  MapInit( Entries&& entries ) {
    do_in_order([&](){ AddToMap(entries); }...);
  } 
};
template<typename... Entries>
MapInit mapInit( Entries&&... entries ) {
  return MapInit( std::forward<Entries>(entries)... );
}
const std::map<std::string, colors> = mapInit( MapEntry<RED>("red"), MapEntry<GREEN>("green") );

它为您提供了一种 C++11 方法来构建 std::map从编译时间color和运行时 string数据。

接下来将“MapEntry<colors> 的列表| 放入colors 的列表”元函数。

template<colors... Cs>
struct color_list {};
template<typename... Ts>
struct type_list {};
template<typename MapEnt>
struct extract_color;
template<colors C>
struct extract_color<MapEntry<C>> {
  enum {value=C};
};
template<typename Entries>
struct extract_colors;
template<typename... MapEntries>
struct extract_colors<type_list<MapEntries...>> {
  typedef color_list< ( (colors)extract_colors<MapEntries>::value)... > type;
};

对该列表进行排序。检测重复项——如果有,那你就搞砸了。

编译时排序比其余部分和 100 多行代码更难。如果你不介意太多,我会把它留在外面! Here is a compile time merge sort I wrote in the past to answer a stack overflow question这将适用于相对简单的改编(它使用值对类型进行排序,在这种情况下,我们直接对编译时值列表进行排序)。

// takes a sorted list of type L<T...>, returns true if there are adjacent equal
// elements:
template<typename clist, typename=void>
struct any_duplicates:std::false_type {};
template<typename T, template<T...>class L, T t0, T t1, T... ts>
struct any_duplicates< L<t0, t1, ts...>, typename std::enable_if<t0==t1>::type>:
  std::true_type {};
template<typename T, template<T...>class L, T t0, T t1, T... ts>
struct any_duplicates< L<t0, t1, ts...>, typename std::enable_if<t0!=t1>::type>:
  any_duplicates< L<t1, ts...> > {};

检测 colors 有效范围之外的元素(即 <MIN_COLOR>=MAX_COLOR )。如果是这样,你就搞砸了。

 template<typename List>
 struct min_max;
 template<typename T, template<T...>class L, T t0>
 struct min_max {
   enum {
     min = t0,
     max = t1,
   };
 };
 template<typename T, template<T...>class L, T t0, T t1, T... ts>
 struct min_max {
   typedef min_max<L<t1, ts...>> rest_of_list;
   enum {
     rest_min = rest_of_list::min,
     rest_max = rest_of_list::max,
     min = (rest_min < t0):rest_min:t0,
     max = (rest_max > t0):rest_max:t0,
   };
 };
 template< typename T, T min, T max, typename List >
 struct bounded: std::integral_constant< bool,
   (min_max<List>::min >= min) && (min_max<List>::max < max)
 > {};

计算有多少个元素——应该有MAX_COLOR元素。如果不是,那你就搞砸了。

 template<typename List>
 struct element_count;
 template<typename T, template<T...>L, T... ts>
 struct element_count<L<ts...>>:std::integral_constant< std::size_t, sizeof...(ts) > {};

如果这些都没有发生,通过 pigeonhole 你必须已经初始化了它们中的每一个。

唯一缺少的是你可以离开并使用相同的 string对于两个值。作为编译时间 string这很麻烦,只需在运行时检查一下(map 中的条目数等于 colors 初始化后的条目数)。

在 C++03 中这样做会更难。你缺少 variardic 模板,所以你最终不得不伪造它们。这是一种痛苦。 mpl也许可以在这方面为您提供帮助。

Variardic 模板在 2012 年 11 月的 MSVC CTP 编译器更新中可用。

这是一个玩具示例,没有重复检查和边界检查(它只是检查 map 条目的数量是否匹配);

#include <cstddef>
#include <utility>
#include <string>
#include <map>

enum TestEnum {
   BeginVal = 0,
   One = BeginVal,
   Two,
   Three,
   EndVal
};

template<TestEnum e>
struct MapEntry {
  enum { val = e };
  std::string s;
  MapEntry( std::string s_ ):s(s_) {}
};

void do_in_order() {}
template<typename F0, typename... Fs>
void do_in_order(F0&& f0, Fs&&... fs) {
  std::forward<F0>(f0)();
  do_in_order( std::forward<Fs>(fs)... );
}

template<typename... MapEntries>
struct count_entries:std::integral_constant< std::size_t, sizeof...(MapEntries) > {};

// should also detect duplicates and check the range of the values:
template<typename... MapEntries>
struct caught_them_all:
  std::integral_constant<
    bool,
    count_entries<MapEntries...>::value == (TestEnum::EndVal-TestEnum::BeginVal)
  >
{};

struct BuildMap {
  typedef std::map<std::string, TestEnum> result_map;
  mutable result_map val;
  operator result_map() const {
    return std::move(val);
  }
  template<typename... MapEntries>
  BuildMap( MapEntries&&... entries ) {
    static_assert( caught_them_all<MapEntries...>::value, "Missing enum value" );
    bool _[] = { ( (val[ entries.s ] = TestEnum(MapEntries::val)), false )... };
  }
};

std::map< std::string, TestEnum > bob = BuildMap(
  MapEntry<One>("One")
  ,MapEntry<Two>("Two")
#if 0
  ,MapEntry<Three>("Three")
#endif
);

int main() {}

替换 #if 0#if 1观看它编译。 Live link如果你想玩。

关于c++ - 编译时检查字符串到枚举映射是否完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045734/

相关文章:

c++ - 访问派生类中的基类成员

C++ const-cast 引用

java - 什么是 Java 中的代理项范围和代理项代码?

c++ - 我如何告诉 gcc 警告我字符串被分配了一个整数值?

c# - 当字符串在资源中时,为什么 String.Format 无法转义字符?

animation - 处理中的 3D SVG 动画——闪烁问题、svg 加载问题

performance - 防止 OpenJPA N+1 在 map 上选择性能问题

c++ - 为 Windows 10/8 x64 创建应用程序需要哪些 qt 组件?

c++ - 字谜程序测试

java - 将 Java 对象转换为 Java Map<String,Object>