【发布时间】:2020-12-26 14:45:59
【问题描述】:
我开始使用std::ranges 并想了解视图的真正工作原理。所以我尝试编写自己的容器和迭代器类型,并希望在视图中使用它。
但似乎缺少一些东西,但编译器只告诉我视图中没有 begin() 方法,但没有告诉我原因。
例子:
#include <iostream>
#include <array>
#include <ranges>
class MyFixedContainer;
class MyIterator
{
MyFixedContainer* ptr;
unsigned int offset;
public:
MyIterator( MyFixedContainer* ptr_, unsigned int offset_ ): ptr{ ptr_},offset{offset_}{}
bool operator==( MyIterator& other ) const
{
return ( ptr == other.ptr )&& ( offset == other.offset );
}
bool operator!=( MyIterator& other ) const
{
return !(*this == other);
}
MyIterator operator++()
{
offset++;
return *this;
}
MyIterator operator++(int)
{
MyIterator tmp = *this;
offset++;
return tmp;
}
int operator*() const;
};
class MyFixedContainer
{
std::array<int,4> arr={5,6,7,8};
public:
auto begin() { return MyIterator{ this, 0 }; }
auto end() { return MyIterator{ this, 4}; }
int Get( int offset ) const
{
return arr[ offset ];
}
};
int MyIterator::operator*() const
{
return ptr->Get( offset );
}
int main()
{
MyFixedContainer c;
// Container type itself works:
for ( int i: c )
{
std::cout << i << std::endl;
}
// Try to use with std::ranges
auto even = [] (int i) { return 0 == i % 2; };
auto y = std::views::filter(c, even);
auto b = y.begin(); // << error message
}
编译
main.cpp:90:16: 错误:'struct std::ranges::views::__adaptor::_RangeAdaptorClosurestd::ranges::views::__adaptor::_RangeAdaptor<:operator main>&}>::
>' 没有名为 'begin' 的成员 90 |自动 b = y.begin();
【问题讨论】:
-
通过编译您的代码(添加包含后),我收到的第一条消息是
'MyFixedContainer' does not name a type。 wandbox.org/permlink/XUwpnVHerzhb9q1R -
@克劳斯,我知道,我只是指出如果我们可以简单地复制&粘贴&编译并得到同样的错误会更好。
-
基本上是我以前的question的骗子。
标签: c++ c++20 std-ranges