c++ - 在 C++ 中重载模板类的 [] 运算符,get 和 set

标签 c++ templates operator-overloading set square-bracket

基本上,我正在尝试为 C++ 制作模板映射/字典类(我知道这已经完成,假设我是受虐狂)。

我开始写这个骨架:

#pragma once
template <class T>
class AssArray
{
    int _size;
    int _position;

public:
    AssArray(int size);
    ~AssArray(void);

    const T& operator [](char* b) const;
    T& operator [](char* b) const;
        //I read this should be done sth like this when researching, though an explanation would be nice.
};

现在,我需要能够获取 (T=AssArray["llama"])、设置 (AssArray["llama"]= T) 和覆盖 (AssArray["llama"]= newT)。

这样做非常简单,只需循环等,这里真正的问题是运算符;

如果我使用 AssArray["llama"]= T,我应该如何将 T 的值放入运算符重载函数中?

我只找到了简单描述解决方案的解释,并不能真正理解。
请赐教。

最佳答案

您所要做的就是像这样更正您的签名:

const T& operator [](char* b) const;
T& operator [](char* b);

我已经从第二个运算符中删除了 const 限定符。

if I use AssArray["llama"]=T, how am I supposed to get the value of T into the operator overloading-function?

你不知道。您只需返回对新值应存储位置的引用,编译器将处理其余部分。如果 "llama" 不存在于数组中,您需要为其创建一个条目,并返回对该条目的引用。

关于c++ - 在 C++ 中重载模板类的 [] 运算符,get 和 set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840885/

相关文章:

c++ - 具有默认模板参数的参数包

C++ 垃圾收集、模板和运算符覆盖 - 无法理解为什么会抛出错误

c++ - 派生重载运算符,但仅对相同类型进行运算

c++ - 重载 operator<< 用于 ostream

c++ - 我可以将 braced-init-list 用于 std::variant 的 vector 吗?

c++ - 如何进行一维 "valid"卷积?

c++ - vtables 和 this 指针

c++ - 使用引用生成 IBM Rhapsody 访问器

c++ - 混合模板与 std::enable_if_t 和特化

c++ - 从包装器接口(interface)动态转换