2017-06-02 136 views
8

我有一個類,我們稱之爲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,但沒有幫助。

+0

請參閱[什麼是暴露自定義STL樣式迭代的首選方法?](https://stackoverflow.com/questions/39231664/what-is-the-preferred-way-to-expose-custom- stl-style-iteration) –

+0

[我應該何時使用新的ranged-for,並且可以將它與新的cbegin/cend結合?](https://stackoverflow.com/questions/5814553/when-should-我使用的最新遠程換和可-I-結合,它與 - 的 - 新的cbegin-CE) –

回答

8

我必須執行開始/結束嗎?

是的。

據我的理解是,它應該選擇cbegin/cend如果它const auto &x,而不是auto &x

這不是如何在標準中定義基於範圍的for。基於範圍的for總是尋找begin()end()。從https://timsong-cpp.github.io/cppwp/n3337/stmt.ranged

否則,開始-EXPR最終EXPRbegin(__range)end(__range),分別,其中beginend中查找與參數相關的查找([basic.lookup.argdep])。爲了查找這個名稱,namespace std是一個關聯的名稱空間。