我有一個類,我們稱之爲ConstVector,它只定義了cbegin/cend而不是開始/結束,因爲我不想在構造之後允許修改其成員。我試圖用基於for循環這樣的範圍內:對於基於循環的範圍,cbegin/cend不夠嗎?
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
我問題是:我是否必須實施開始/結束?據我瞭解,它應該選擇cbegin/cend,如果它是const auto &x
而不是auto &x
。至少這對我來說是有意義的。如果我刪除基於循環的範圍,一切都編譯好。
我也嘗試幾乎所有建議here使它const
,但沒有幫助。
請參閱[什麼是暴露自定義STL樣式迭代的首選方法?](https://stackoverflow.com/questions/39231664/what-is-the-preferred-way-to-expose-custom- stl-style-iteration) –
[我應該何時使用新的ranged-for,並且可以將它與新的cbegin/cend結合?](https://stackoverflow.com/questions/5814553/when-should-我使用的最新遠程換和可-I-結合,它與 - 的 - 新的cbegin-CE) –