自定义枚举模板类

时间:2017-07-28 07:43:18

标签: c++ c++11

我想编写自己的枚举类来扩展默认枚举类的功能 - 比如显式转换为字符串,迭代枚举等等。因为我不知道从哪里开始我问强大谷歌发现了this(相当古老)的博文。我根据我的需要调整了类,并修复了一些编译器问题,并提出了以下模板

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(); }

};

我尝试使用它时出现的问题。由于m_sInstances是静态成员,因此需要在模板外部实例化,如下所示:

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");

m_sInstances的特化使链接搞砸了,让构建失败了:

  

对“Enum :: m_sInstances”

的未定义引用

有没有办法避免这种情况?我想不出任何解决方案。

0 个答案:

没有答案
相关问题