枚举不适用于类似代码的模板

enum won't work with template like code

我试图通过 STL 模仿 boost::iterator_range 和 boost::counting_iterator。代码似乎可以工作,但是当我尝试将枚举元素传递给它时,出现以下错误:

Error 2 error C2100: illegal indirection
Error 1 error C2675: unary '++' : '`anonymous-namespace'::Block_Edges' does not define this operator or a conversion to a type acceptable to the predefined operator

如何修复这些错误?

代码

#include <iostream>

namespace
{
    enum Block_Edges
    {
        FROM = 0,
        TO = 4,
    };
};

template<typename T, bool enable = std::is_integral<T>::value>
struct range_impl
{
    struct iterator
    {
        const T operator * ()const noexcept
        {
            return value;
        }

        iterator& operator ++() noexcept
        {
            ++value;
            return *this;
        }

        friend  const bool operator != (const iterator& lhs, const iterator& rhs) noexcept
        {
            return lhs.value != rhs.value;
        }

        T value;
    };

    std::size_t size() const
    {
        return last - first;
    }

    const iterator begin()const noexcept
    {
        return{ first };
    }

        const iterator end()const noexcept
    {
        return{ last };
    }

    T first;
    T last;
};

template<typename T>
struct range_impl<T, false>
{
    range_impl(T first, T last)
        : first(first)
        , last(last)
    {}

    std::size_t size() const
    {
        return std::distance(first, last);
    }

    const T begin()const noexcept
    {
        return{ first };
    }

        const T end()const noexcept
    {
        return{ last };
    }

    T first;
    T last;
};

template<typename T>
range_impl<T>  range(T first, T last) noexcept
{
    return{ first, last };
}

int main()
{
    //for (const auto& i : range(0, 4)) // PASS
    //{
    //  std::cout << '\n' << i << ':';
    //  for (const auto& j : range(0, 4))
    //  {
    //      std::cout << j << ' ';
    //  }
    //}

    for (const auto& i : range(Block_Edges::FROM, Block_Edges::TO)) // FAILED
    {
        std::cout << '\n' << i << ':';
        for (const auto& j : range(Block_Edges::FROM, Block_Edges::TO))
        {
            std::cout << j << ' ';
        }
    }
}

已解决:

只是转换为 int。

您有 2 个错误:

缺少此功能:

Block_Edges& operator++(Block_Edges& e)
{
    return e = static_cast<Block_Edges>(e + 1);
}

枚举在 C++ 中不被视为整数类型,因此您还必须使用 std::is_enum:

template<typename T,
         bool enable = std::is_integral<T>::value || std::is_enum<T>::value>
struct range_impl

Live example