我正在尝试std :: map,使用枚举类和std :: string但是我收到了一些错误。 我正在使用gcc 4.4.7和-std = c ++ 0x(这是固定的)
在.h档案:
enum class state_t{
unknown,
off,
on,
fault
};
typedef std::map<state_t,std::string> statemap_t;
在.cpp文件:
statemap_t state={
{state_t::unknown,"unknown"}
{state_t::off,"off"}
{state_t::on,"on"}
{state_t::fault,"fault"}
}
允许状态转换的方法如下:
Foo::allowStateChange(const state_t localState, const state_t globalState, const state_t newState){
//Some code to verify if the state transition is allowed.
std::cout << "Device Local State:" << state.find(localState)->second << "Device Global State:" << state.find(globalState)->second << "Device New State:" << state.find(newState)->second << std::endl;
}
在进行计算时,我会收到下一个错误: 错误:类型的无效操作数&#39; state_t&#39;和&#39; state_t&#39;到二元&#39;运算符&lt;&#39;
如果我将enum class state_t
更改为enum state_t
则可行。
有没有办法在地图中找到枚举类?
提前致谢。
答案 0 :(得分:2)
以下代码工作正常(在Visual Studio 2015(v140)上;在您的情况下使用哪个编译器?):
#include <string>
#include <iostream>
#include <map>
using namespace std;
enum class state_t {
unknown,
off,
on,
fault
};
typedef std::map<state_t, std::string> statemap_t;
statemap_t state = {
{ state_t::unknown,"unknown" },
{ state_t::off,"off"},
{ state_t::on,"on"},
{ state_t::fault,"fault"}
};
void allowStateChange(const state_t localState, const state_t globalState, const state_t newState) {
//Some code to verify if the state transition is allowed.
std::cout
<< "Device Local State:"
<< state.find(localState)->second
<< ", Device Global State:"
<< state.find(globalState)->second
<< ", Device New State:"
<< state.find(newState)->second
<< std::endl;
}
int main()
{
allowStateChange(state_t::on, state_t::off, state_t::fault);
return 0;
}
BWT,state_t中有一个拼写错误的“unkmown”。
答案 1 :(得分:0)
我假设您使用的GCC编译器版本不支持与枚举类关联的所有基础结构。因此,您需要自己实现缺少的运算符,如下所示:
inline bool operator <(const state_t left, const state_t right)
{
return static_cast<int>(left) < static_cast<int>(right);
}
inline bool operator >(const state_t left, const state_t right)
{
return static_cast<int>(left) > static_cast<int>(right);
}
在C ++ 11中,这些功能可能是通过模板专门化来实现的,对static_cast使用std :: underlying_type并将限定词专门与枚举类绑定,其中某些可能在-std = c ++ 0x下不可用特定的编译器版本