2016-03-08 58 views
0

下將正常工作,直到我需要一個非const引用:功能以矢量,索引並返回元素

template <typename T> 
T const& get(std::vector<T> const& vec, size_t i) { return vec[i]; } 

如果我改變返回類型T &,事遂所願get(vec, 0).push_back(3)就可以了(如果vec是整數向量的向量)。然而,如果訪問一個整數向量(而不是向量的向量),我們得到:

error: binding ‘const value_type {aka const int}’ 
to reference of type ‘int&’ discards qualifiers 

有沒有一種方法,使具有相同功能都工作?

更新:在下面的答案中給出的建議,除了vector<bool>。我在這裏張貼的細節吧:

template <typename T> 
T const& get(std::vector<T> const& vec, size_t i) { return vec[i]; } 

template <typename T> 
T & get(std::vector<T> & vec, size_t i) { return vec[i]; } 

int main() { 
    std::vector<bool> vec_bool{true,true,false}; 
    std::cout << get(vec_bool, 0) << std::endl; 
} 

g++ --std=c++11 test.cc編譯給出:

test.cc: In instantiation of ‘T& get(std::vector<T>&, size_t) [with T = bool; size_t = long unsigned int]’: 
test.cc:12:30: required from here 
test.cc:8:55: error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘bool’ 
    T & get(std::vector<T> & vec, size_t i) { return vec[i]; } 
                 ^
In file included from /usr/include/c++/5/vector:65:0, 
        from test.cc:1: 
/usr/include/c++/5/bits/stl_bvector.h:80:5: note: after user-defined conversion: std::_Bit_reference::operator bool() const 
     operator bool() const _GLIBCXX_NOEXCEPT 

編譯器版本:G ++(Ubuntu的5.3.1-10ubuntu2)5.3.1 20160225

+0

應該有載體的載體和載體,如果'int'之間沒有什麼區別。請發佈一個MCVE。 – juanchopanza

+0

你確定它可以用於矢量矢量嗎?它不應該 –

+0

你確定你沒有試圖訪問'const int'的向量嗎?錯誤消息表明你這樣做。 –

回答

1

std::vector報價two overloadsoperator[],非const和const版本。

由於你的get函數接受一個const向量,索引該向量總是會調用常量版本operator[],它返回一個const引用。因此,與返回類型不匹配,因爲您無法將const int轉換爲int&const vector<vector<...>>轉換爲vector<vector<...>>&。我很好奇你在使用矢量矢量時沒有遇到錯誤。

您將不得不提供此功能的兩個版本。一個採用非常量向量並返回非常量參考,另一個採用const向量並返回一個常量參考。

而這與使用標準operator[]相同,但是具有額外的間接層。

編輯:又見這個問題 - Is there any difference between 「T」 and 「const T」 in template parameter?

+0

「......但有一個間接的額外層」這可能是你的答案中最重要的細節。我仍然想知道爲什麼這種間接性是必要的(因爲某種兼容層可能?)。 – 2016-03-08 15:02:33

+0

它可以工作,除了'vector ',它可能連接到https://en.wikipedia.org/wiki/Sequence_container_%28C%2B%2B%29#Specialization_for_bool。 –

+0

@Boris我可以看到這被用作'operator []'的包裝來檢查索引的有效性。 – aslg