对boost::filtered_range值的引用类型

Type of reference to boost::filtered_range value

本文关键字:range 引用类型 boost filtered      更新时间:2023-10-16

我想向boost::filtered_range类添加一个运算符[]。这是我的代码:

template <typename TPredicate, typename TRange>
class my_filtered_range : public boost::filtered_range<TPredicate, TRange>
{
public:
    my_filtered_range(TPredicate Predicate, TRange &Range) : boost::filtered_range<TPredicate, TRange>(Predicate, Range)
    {
    }
    size_t size() const
    {
        return std::distance(begin(), end());
    }
    ???? &operator[](size_t Index) const
    {
        assert(Index < size());
        auto It = begin();
        std::advance(It, Index);
        return *It;
    }
};

问题是使用什么类型作为运算符[]的返回类型?指定"value_type"不允许将类与"const"容器一起使用,"decltype(*begin())"不使用我的VC++2013进行编译。

您应该能够在基类上使用boost::range_reference<>特性。

在Coliru上直播

#include <boost/range/adaptors.hpp>
template <typename TPredicate, typename TRange>
class my_filtered_range : public boost::filtered_range<TPredicate, TRange>
{
public:
    typedef boost::filtered_range<TPredicate, TRange> base_type;
    my_filtered_range(TPredicate Predicate, TRange &Range) : boost::filtered_range<TPredicate, TRange>(Predicate, Range)
    {
    }
    size_t size() const
    {
        return std::distance(this->begin(), this->end());
    }
    typename boost::range_reference<const base_type>::type operator[](size_t Index) const
    {
        assert(Index < this->size());
        auto It = this->begin();
        std::advance(It, Index);
        return *It;
    }
};

请注意,我是如何检测到您使用了一个损坏的编译器(MSVC)的,因此我为依赖的基成员和类型添加了必要的限定条件。