哇,好长的标题。
这是我的问题。我在 C++ 中有一个模板类,我正在重载 [] 运算符。我有一个 const 和一个非常量版本,非常量版本通过引用返回,这样类中的项目就可以这样更改:
myobject[1] = myvalue;
这一切都有效,直到我使用 bool 值作为模板参数。这是显示错误的完整示例:
#include <string>
#include <vector>
using namespace std;
template <class T>
class MyClass
{
private:
vector<T> _items;
public:
void add(T item)
{
_items.push_back(item);
}
const T operator[](int idx) const
{
return _items[idx];
}
T& operator[](int idx)
{
return _items[idx];
}
};
int main(int argc, char** argv)
{
MyClass<string> Test1; // Works
Test1.add("hi");
Test1.add("how are");
Test1[1] = "you?";
MyClass<int> Test2; // Also works
Test2.add(1);
Test2.add(2);
Test2[1] = 3;
MyClass<bool> Test3; // Works up until...
Test3.add(true);
Test3.add(true);
Test3[1] = false; // ...this point. :(
return 0;
}
错误是编译器错误,消息是:
error: invalid initialization of non-const reference of type ‘bool&’ from a temporary of type ‘std::_Bit_reference’
我已经阅读并发现 STL 使用了一些临时数据类型,但我不明白为什么它适用于除 bool 之外的所有数据类型。
如有任何帮助,我们将不胜感激。
最佳答案
因为 vector<bool>
专攻STL,实际上不符合标准容器的要求。
Herb Sutter 在 GOTW 文章中对此进行了更多讨论:http://www.gotw.ca/gotw/050.htm
关于c++ - 在具有 const/nonconst 版本的 C++ 模板类上重载 [] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3458856/