Click here to Skip to main content
13,247,005 members (78,070 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


15 bookmarked
Posted 16 Jul 2012

Enum mapping with compile time lookup

, 16 Jul 2012
Rate this:
Please Sign up or sign in to vote.
Using C++ templates to convert from Enum value to whatever mapped value


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:

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.

namespace MyEnum
    enum Enum { Val1, VAL2 };

    class MyEnumMapper
        : public EnumValue<MyEnum::VAL1>
        , public EnumValue<MyEnum::VAL2>
        , public EnumMapper<MyEnumMapper,MyEnum::Enum>

    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
template<typename MappedType>
class EnumValueList
    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>
    EnumValue(const MappedType& mappedValue) : m_MappedValue(mappedValue)
    MappedType m_MappedValue;
    enum Enum { Enum = EnumVal };

template<class Mapper, typename EnumType, typename MappedType = std::string>
class EnumMapper
    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();

    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.


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


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


About the Author

Rolf Kristensen
Software Developer
Denmark Denmark
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionWhy not std::map<> or boost::bimap<>? Pin
tbrammer12-Aug-12 22:55
membertbrammer12-Aug-12 22:55 
AnswerRe: Why not std::map or boost::bimap? Pin
Rolf Kristensen13-Aug-12 11:50
memberRolf Kristensen13-Aug-12 11: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 17 Jul 2012
Article Copyright 2012 by Rolf Kristensen
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid