I'm having issues using an enum class as a type specifier within an unordered_map.
I've trawled the internet but had no luck with any of the solutions.
Closest example I found was at the link below, but seemingly doesn't work. Can't use enum class as unordered_map key
Running on an STM32F4103 if it matters.
foo.h
#include <cstring>
#include <unordered_map>
#include <functional>
class Foo
{
public:
enum class COLOURS : uint16_t
{
RED,
YELLOW,
BLUE,
GREEN
};
static const std::unordered_map<COLOURS, std::string, EnumClassHash> colours_map;
};
foo.cpp
#include "foo.h"
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
std::unordered_map<Foo::COLOURS, std::string, EnumClassHash> Foo::colours_map
{
{Foo::COLOURS::RED, "red"},
{Foo::COLOURS::YELLOW, "yellow"},
{Foo::COLOURS::BLUE, "blue"},
{Foo::COLOURS::GREEN, "green"}
};
The above compiles fine, I've omitted the main, but basically construct the class and get the string associated to a specified colour.
However, it crashes the chip. My suspicion is that the hash has computed incorrectly??
Complete newbie to hashing so layman's terms or a code snippet would be greatly appreciated.
TIA
EDIT:
So thank you for the help so far. Issue still persists but I can be more specific now.
The following foo.h and a corresponding empty foo.cpp compiles and runs fine:
foo.h
#include <unordered_map>
#include <cstdint>
#include <functional>
#include <string>
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
class Foo {
public:
Foo() :
colours_map(
{
{COLOURS::RED, "red"},
{COLOURS::YELLOW, "yellow"},
{COLOURS::BLUE, "blue"},
{COLOURS::GREEN, "green"}
}
)
{
;
}
enum class COLOURS: uint16_t {
RED,
YELLOW,
BLUE,
GREEN
};
const std::unordered_map<COLOURS, std::string, EnumClassHash> colours_map;
};
However, I really need this to be static for my application. The following, compiles fine but crashes the chip. As far as I can tell using openOCD the chip doesn't even boot. Odd given that it works fine here https://wandbox.org/permlink/xm37mOGjYFbOjc7I
foo.h
#include <unordered_map>
#include <cstdint>
#include <functional>
#include <string>
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
class Foo {
public:
enum class COLOURS: uint16_t {
RED,
YELLOW,
BLUE,
GREEN
};
static const std::unordered_map<COLOURS, std::string, EnumClassHash> colours_map;
};
foo.cpp
#include "foo.h"
const std::unordered_map<Foo::COLOURS, std::string, EnumClassHash> Foo::colours_map {
{Foo::COLOURS::RED, "red"},
{Foo::COLOURS::YELLOW, "yellow"},
{Foo::COLOURS::BLUE, "blue"},
{Foo::COLOURS::GREEN, "green"}
};
...I feel I am missing something very obvious. TIA