Click here to Skip to main content
15,885,985 members
Articles / Programming Languages / C++

Enum mapping with compile time lookup

Rate me:
Please Sign up or sign in to vote.
4.38/5 (5 votes)
16 Jul 2012CPOL1 min read 24.4K   16   2
Using C++ templates to convert from Enum value to whatever mapped value

Introduction

When mapping from an Enum value to a mapped string value, then one usually traverse a conversion-map with whatever overhead. Then one also have to implement some extra error handling for the situation where the conversion-map is incomplete.

I wanted to write the following:

C++
std::string hello1 = MyEnum::Mapper.GetMapped<MyEnum::VAL1>();

The quick workaround would just be to hardcode the mapped value, but then I needed to maintain another set of named string-values. This would require some special mechanism/guidelines to ensure that they were properly mapped to their corresponding enum value and didn't become stale.

Using the code

The solution was to implement the mapping using inheritance and then use static_cast to check if there is a valid mapping from a given enum value.

C++
namespace MyEnum
{
    enum Enum { Val1, VAL2 };

    class MyEnumMapper
        : public EnumValue<MyEnum::VAL1>
        , public EnumValue<MyEnum::VAL2>
        , public EnumMapper<MyEnumMapper,MyEnum::Enum>
    {
    public:
        MyEnumMapper()
            :EnumValue<MyEnum::VAL1>("Hello1")
            ,EnumValue<MyEnum::VAL2>("Hello2")
        {}
    };

    static MyEnumMapper Mapper;
};


int _tmain(int argc, _TCHAR* argv[])
{
    std::string val1 = MyEnum::Mapper.GetMapped<MyEnum::VAL1>(); // Compile time checked
    std::string val2 = MyEnum::Mapper.GetMapped<MyEnum::VAL2>(); // Compile time checked
    val2 = MyEnum::Mapper.GetMapped(1); // Unsafe mapping
    MyEnum::Enum myEnum1 = MyEnum::Mapper.GetEnum(val1); // Unsafe mapping
    MyEnum::Enum myEnum2 = MyEnum::Mapper.GetEnum(val2); // Unsafe mapping
    myEnum2 = MyEnum::Mapper.GetEnum("Hello2"); // Unsafe mapping

    return 0;
}

If one suddenly have to extend MyEnum with a new enum VAL3 value, then one will get a compile error if trying to use the new enum before having updated MyEnumMapper.

The code behind the scenes

These are the classes involved in this enum mapping:

  • EnumMapper - Performs the actual mapping and validation. Either runtime or compile time.
  • EnumValue - Registration of a single Enum mapping
  • EnumValueList - Keeps track of all the registered Enum mappings
C++
template<typename MappedType>
class EnumValueList
{
public:
    std::vector< std::pair<int,MappedType> > m_EnumValues;
};

// Performs virtual inheritance so there is only one EnumValueList within a single mapper
template<int EnumVal, typename MappedType = std::string>
class EnumValue : public virtual EnumValueList<MappedType>
{
public:
    EnumValue(const MappedType& mappedValue) : m_MappedValue(mappedValue)
    {
        m_EnumValues.push_back(std::make_pair(EnumVal,mappedValue));
    }
    MappedType m_MappedValue;
    enum Enum { Enum = EnumVal };
};

template<class Mapper, typename EnumType, typename MappedType = std::string>
class EnumMapper
{
public:
    typedef typename std::vector< typename std::pair<int,MappedType> > EnumValues;
    typedef typename EnumValues::const_iterator iterator;

    // Compile type validation of enum-type and conversion to mapped value
    template<EnumType EnumVal>
    const MappedType& GetMapped() const
    {
        return static_cast< const EnumValue<EnumVal,MappedType>& >
            ( (const Mapper&)*this ).m_MappedValue;
    }

    const MappedType& GetMapped(int enumValue) const
    {
        for(iterator it = begin() ; it != end() ; ++it)
            if(it->first == enumValue)
                return it->second;

        assert( ("Unknown enum value", false) );
        return begin()->second; // Expects first to be unknown
    }

    EnumType GetEnum(const MappedType& mappedValue) const
    {
        for(iterator it = begin() ; it != end() ; ++it)
            if(it->second == mappedValue)
                return (EnumType)it->first;

        assert( ("Unknown mapped value", false) );
        return (EnumType)begin()->first; // Expects first to be unknown
    }

    const EnumValues& GetEnumValues() const
    {
        return static_cast< const EnumValueList<MappedType>& >
            ( (const Mapper&)*this ).m_EnumValues;
    }

    typename iterator begin() const
    {
        return GetEnumValues().begin();
    }

    typename iterator end() const
    {
        return GetEnumValues().end();
    }

protected:
    template<EnumType EnumVal>
    void AddMapping(const MappedType& mappedValue)
    {
        static_cast< EnumValueList<MappedType>& >( (Mapper&)*this ).
            m_EnumValues.push_back( std::make_pair(EnumVal,mappedValue) );
    }
};

Points of Interest

I wanted the EnumValue class to have the entire mapping as template arguments, but apparently it is not possible to use a string literal as template parameter. So I had to settle with performing the actual mapping using the EnumValue constructor, and accept the extra typing.

History

  • 2012-07-16 - Initial revision
  • 2012-07-17 - Now uses EnumValue constructor to initialize mapping

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhy not std::map<> or boost::bimap<>? Pin
tbrammer12-Aug-12 21:55
professionaltbrammer12-Aug-12 21:55 
AnswerRe: Why not std::map or boost::bimap? Pin
Rolf Kristensen13-Aug-12 10:50
Rolf Kristensen13-Aug-12 10:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.