下將正常工作,直到我需要一個非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
應該有載體的載體和載體,如果'int'之間沒有什麼區別。請發佈一個MCVE。 – juanchopanza
你確定它可以用於矢量矢量嗎?它不應該 –
你確定你沒有試圖訪問'const int'的向量嗎?錯誤消息表明你這樣做。 –