FKa*_*ria 7 c++ string enums map c++11
这个问题很可能是"如何将字符串映射到枚举"的第n次迭代.
我的要求更进一步,throw
当在有效输入范围内找不到密钥时,我想要一个例外.所以我有这个实现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;
}
Run Code Online (Sandbox Code Playgroud)
这很好,并做我需要的.现在,我希望能够在编译时知道某个元素中的所有元素enum
都传递给EnumMap
构造函数,并且所有元素enum
都与相应的字符串匹配.
我尝试使用std :: initializer_list和static_assert,但似乎VC2010仍然不支持std::initializer_list
(参见此处).
有没有人知道如何实现这个?也许使用模板,或实现我自己的Enum类?
归档时间: |
|
查看次数: |
2263 次 |
最近记录: |