Custom enumeration template template

I wanted to write my own enum class to slightly expand the capabilities of the default enumeration classes - for example, explicit conversions to strings, enumeration iteration, etc. Since I did not know where to start, I asked the powerful Google and found this (rather old) blog post. I adapted the class to my needs and fixed some problems with the compiler and came up with the following pattern

template < typename T >
class Enum {    
private:
    int m_iValue;
    const char* m_sName;

    // comparator for the set
    struct EnumPtrLess {
        bool operator() (const Enum<T>* lhs, const Enum<T>* rhs) {
            return lhs->m_iValue < rhs->m_iValue;
        }
    };

protected:
    static std::set<const Enum<T>*, EnumPtrLess> m_sInstances;

    explicit Enum(int iVal, const char* sName) 
        : m_iValue(iVal)
        , m_sName(sName)
    {
        m_sInstances.insert(this); // store the object inside the container
    }

public:
    typedef std::set<const Enum<T>*, EnumPtrLess> instance_list;
    typedef typename instance_list::const_iterator const_iterator;
    typedef typename instance_list::size_type size_type;
    // convenient conversion operators
    operator int() const { return m_iValue; }
    explicit operator std::string() const { return m_sName; }

    static const Enum<T>* FromInt(int iValue) 
    {
        const_iterator it = std::find_if(m_sInstances.begin(), m_sInstances.end(), 
            [&](const Enum<T>* e) { return e->m_iValue == iValue; } );
        return (it == m_sInstances.end() ? NULL : *it);
    }

    static size_type Size() { return m_sInstances.size(); }

    static const_iterator begin() { return m_sInstances.begin(); }
    static const_iterator end() { return m_sInstances.end(); }

};

The problem that I see appears when I try to use it. Since it m_sInstancesis a static member, it must be created outside the template, as shown below:

class EDirection : public Enum<EDirection> {
private:
    explicit EDirection(int iVal, const char* sName) 
        : Enum<EDirection>(iVal, sName)
    {}
public:
    static const EDirection NORTH;
};

template <> Enum<EDirection>::instance_list Enum<EDirection>::m_sInstances;

const EDirection EDirection::NORTH(1, "NORTH");

Specialization m_sInstancestightens the connection and allows the assembly to fail:

undefined link to "Enum :: m_sInstances"

? .

+4

Source: https://habr.com/ru/post/1682466/


All Articles