gpt4 book ai didi

c++ - cbegin/cend 是否不足以用于基于范围的 for 循环?

转载 作者:可可西里 更新时间:2023-11-01 16:38:01 25 4
gpt4 key购买 nike

我有一个类,我们称它为 ConstVector,它只定义 cbegin/cend 而不是 begin/end,因为我不想在构造后对其成员进行修改。我尝试像这样使用基于范围的 for 循环:

ConstVector const_vector(1, 2, 3);
for(const auto &x : const_vector)
....

虽然类的相关部分看起来像这样:

template<class T>
class ConstVector
{
public:
ConstVector(std::initializer_list<T> values);
typename std::vector<T>::const_iterator cbegin(void) const;
typename std::vector<T>::const_iterator cend(void) const;

private:
std::vector<T> data;
};

template<class T>
ConstVector::ConstVector(std::initializer_list<T> values)
: data(values)
{
}

template<class T>
typename std::vector<T>::const_iterator ConstVector<T>::cbegin() const
{
return this->data.cbegin();
}

template<class T>
typename std::vector<T>::const_iterator ConstVector<T>::cend() const
{
return this->data.cend();
}

但是我的编译器提示:

‘begin’ was not declared in this scope

我的问题是:我必须实现开始/结束吗?据我了解,如果它是 const auto &x 而不是 auto &x,它应该选择 cbegin/cend。至少这对我来说是有意义的。如果我删除基于范围的 for 循环,一切都可以正常编译。

我也几乎尝试了所有建议 here使其成为 const,但这并没有帮助。

最佳答案

Do I have to implement begin/end?

是的。

As far as I understood it, it should choose cbegin/cend if it's const auto &x and not auto &x.

这不是标准中定义基于范围的 for 的方式。基于范围的 for 总是寻找 begin()end()。来自 https://timsong-cpp.github.io/cppwp/n3337/stmt.ranged .

otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin and end are looked up with argument-dependent lookup ([basic.lookup.argdep]). For the purposes of this name lookup, namespace std is an associated namespace.

关于c++ - cbegin/cend 是否不足以用于基于范围的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332074/

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