【问题标题】:How to std::map<enum class, std::string>?如何 std::map<枚举类,std::string>?
【发布时间】:2017-02-24 11:09:48
【问题描述】:

我正在尝试使用枚举类和 std::string 的 std::map,但我遇到了一些错误。 我正在使用带有 -std=c++0x 的 gcc 4.4.7(这是固定的)

在 .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;
}

编译时,我得到下一个错误: 错误:'state_t'和'state_t'类型的无效操作数到二进制'operator

如果我将 enum class state_t 更改为 enum state_t 它可以工作。 有没有办法在地图中找到枚举类?

提前致谢。

【问题讨论】:

  • 您是否将&lt;&lt; 拼错为&lt;
  • 没有,我查过了
  • 哦,所以这个问题和cout一点关系都没有?只定义地图是否有效?
  • 井图需要 stackoverflow.com/questions/15451382/… 看到示例
  • 无法重现,在 ideone 上的可用编译器上测试。一个example。 (查看@Evgeny 的答案以查看拼写错误和遗漏的逗号)

标签: c++ enums stdmap enum-class


【解决方案1】:

以下代码可以正常工作(在 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”。

【讨论】:

  • 在代码中是可以的,只是拼错了,我没有复制粘贴代码
  • 我正在使用 gcc 4.4.7 (RedHat 4.4.7-4) 。但是我不能修改gcc版本
  • gcc 4.4.7 对于枚举类的支持可能已经相当老了。你可能不得不依赖普通的枚举。
【解决方案2】:

我假设您使用的 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 中,这些函数很可能通过模板特化实现,使用 std::underlying_type 作为 static_cast 和将它们专门绑定到枚举类的限定符,其中一些可能在 -std=c++0x 下不可用对于您的特定编译器版本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2021-11-21
    • 2015-10-22
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多