gpt4 book ai didi

c++ - boost::filtered_range 值的引用类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:20:56 24 4
gpt4 key购买 nike

我想添加一个 operator[] 到 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;
}
};

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

最佳答案

您应该能够使用 boost::range_reference<>基类的特征。

Live On 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),因此我向依赖的基本成员和类型添加了必要的限定条件。

关于c++ - boost::filtered_range 值的引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com