C++ Singleton Enumerated Map

Features

  • Maps enum type literals to strings (or any type)
  • Singleton pattern ensure only single instance
  • Encapsulation checks if key exists to prevent lookup errors/exceptions.

C++17 version

--std=c++17 -Wall -Wextra

#include <map>
#include <string>
#include <iostream>

class EnumMap
{
private:
    EnumMap() {}
public:
    enum etypes { ONE, TWO, THREE };

    static std::string str(EnumMap::etypes e)
    {
        static EnumMap INSTANCE;
        auto search = EnumMap::m_data.find(e);
        return search != EnumMap::m_data.end() ? (*search).second : "";
    }
    static inline std::map<etypes, std::string> m_data =
    {
        {etypes::ONE, "one"},
        {etypes::TWO, "two"},
        {etypes::THREE, "three"}
    };
};

int main()
{
    std::cout << EnumMap::str(EnumMap::TWO) << std::endl;
    std::cout << EnumMap::str(EnumMap::ONE) << std::endl;
}

output:

ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
two
one

C++14 version

--std=c++14 -Wall -Wextra

#include <map>
#include <string>
#include <iostream>

class EnumMap
{
private:
    EnumMap() {}
public:

    enum etypes { ONE, TWO, THREE };

    static std::string str(EnumMap::etypes e)
    {
        static EnumMap INSTANCE;
        auto search = EnumMap::m_data.find(e);
        return search != EnumMap::m_data.end() ? (*search).second : "";
    }
    static const std::map<etypes, std::string> m_data;
};

const std::map<EnumMap::etypes, std::string> EnumMap::m_data =
{
    {EnumMap::etypes::ONE, "one"},
    {EnumMap::etypes::TWO, "two"},
    {EnumMap::etypes::THREE, "three"}
};


int main()
{
    std::cout << EnumMap::str(EnumMap::TWO) << std::endl;
    std::cout << EnumMap::str(EnumMap::ONE) << std::endl;
}

output

ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
two
one

https://godbolt.org/z/PYzvv3P5b

Categories: C++

Leave a Reply

Your email address will not be published. Required fields are marked *