哇,那是一个很长的标题。
这是我的问题。我在 C++ 中有一个模板类,我正在重载 [] 运算符。我有一个 const 和一个非常量版本,非常量版本通过引用返回,以便类中的项目可以这样更改:
myobject[1] = myvalue;
这一切都有效,直到我使用布尔值作为模板参数。这是显示错误的完整示例:
#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 之外的所有内容。
对此的任何帮助将不胜感激。