考虑此类:
#include <vector>
using namespace std;
template<typename T>
class Vector{
private:
size_t size_;
vector<T> items;
public:
Vector(){ size_ = 0; }
inline void clear(){ size_ = 0; }
inline void push_back( const T item ){
if( items.size() == size_ )
items.push_back( item );
else
items[size_] = item;
size_++;
}
inline const T& operator[](int i) const { return items[i]; }
inline T& operator[](int i) { return items[i]; }
};
int main(int argc, char *argv[]){
Vector<bool> vec;
vec.push_back( true );
if( vec[0] )
vec[0] = false;
}
使用MSVS 2013编译时,对于非const运算符[],会出现以下错误:
error C2440: 'return' : cannot convert from 'std::_Vb_reference<std::_Wrap_alloc<std::allocator<char32_t>>>' to 'bool &'
更改
return (T&)(items[i]);
中的return语句会导致警告warning C4238: nonstandard extension used : class rvalue used as lvalue
程序运行(在 Debug模式下),但最后一条语句不会更改
vec[0]
的值(如您所期望的rhv)。怎么了
最佳答案
因为 std::vector<bool>
是特殊的,所以对于std::vector
类型,它是bool
的节省空间的特化。 operator[]
不会返回bool&
或const bool&
,而是一个代表对单个bool
的引用的代理类。