c++ - 在具有 const/nonconst 版本的 C++ 模板类上重载 [] 运算符

标签 c++ templates return-by-reference

哇,好长的标题。

这是我的问题。我在 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/

相关文章:

c++ - “Setter”方法不更改属性,但是测试方法输出“test”吗? (以最少的可复制示例重新提交)

c++ - 除非在调试器中逐步执行,否则函数调用会导致 C++ 程序卡住

c++ - 按属性对特征向量进行多排序的数据结构

c++ - 多维动态内存 vector c++

c++ - C++模板运算符重载实例化

f# - F# 4.5 中的 byref 返回

c++ - 应该重载 operator = 返回 class& 或 class

c++ - 函数模板重载谜题

c++ - 模板类根据它们的存在和优先级调用其他类的一些命名函数

c++ - 从其他类访问非类型模板参数的最佳方法是什么?