我在使用 view_facade (来自range-v3)创建提供 const 和非常量访问的视图时遇到问题。例如,我尝试修改 view_facade 测试(在 test/view_facade.cpp 中)以允许非 const 访问(默认情况下它只允许 const 访问):
struct MyRange
: ranges::range_facade<MyRange>
{
private:
friend struct ranges::range_access;
std::vector<int> ints_;
template <bool isConst>
struct cursor
{
private:
using It = typename std::conditional<isConst, std::vector<int>::const_iterator, std::vector<int>::iterator>::type;
using RefType = typename std::conditional<isConst, int const&, int&>::type;
It iter;
public:
cursor() = default;
cursor(It it)
: iter(it)
{}
RefType current() const
{
return *iter;
}
//...
};
/* // Uncommenting these overloads will cause an error, below.
cursor<true> begin_cursor() const
{
return {ints_.begin()};
}
cursor<true> end_cursor() const
{
return {ints_.end()};
}
*/
cursor<false> begin_cursor()
{
return {ints_.begin()};
}
cursor<false> end_cursor()
{
return {ints_.end()};
}
public:
MyRange()
: ints_{1, 2, 3, 4, 5, 6, 7}
{}
};
int main() {
MyRange nc;
int& nci = *nc.begin(); // error here when const overloads present.
}
这适用于 begin_cursor 和 end_cursor 的 const 重载注释掉。但是,如果我重新添加这些重载,则会在指示的行(GCC 5.1)上生成以下错误:
error: binding 'const int' to reference of type 'int&' discards qualifiers
似乎在选择 const 版本,给了我一个 const 迭代器。我想要的是:用于 const 对象的 const 迭代器,以及用于非 const 对象的非 const 迭代器。我怎样才能做到这一点?