How to std::map<enum class, std::string>?

user2357667 picture user2357667 · Feb 24, 2017 · Viewed 8.4k times · Source

I am trying to std::map, with an enum class and a std::string but I am getting some error. I am using gcc 4.4.7 with -std=c++0x (this is fixed)

At .h file:

enum class state_t{
    unknown,
    off,
    on,
    fault
};

typedef std::map<state_t,std::string> statemap_t;

At .cpp file:

statemap_t state={
   {state_t::unknown,"unknown"}
   {state_t::off,"off"}
   {state_t::on,"on"}
   {state_t::fault,"fault"}
}

The method to allow a state transitionis like:

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

When compilling, I get next error: error: invalid operands of types 'state_t' and 'state_t' to binary 'operator<'

If I change the enum class state_t to enum state_t it works. Is there any way to find in the map with an enum class?

Thanks in advance.

Answer

Evgeny picture Evgeny · Feb 24, 2017

The following code works just fine (on Visual Studio 2015 (v140); which compiler is used in your case?):

#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, there is a misspell "unkmown" in the state_t.